236 Lowest Common Ancestor of a Binary Tree
_______3______
/ \
___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
def path_to_x(root, path, x, go):
if root is not None and go[0]:
path.append(root.val)
if root.val == x:
go[0] = False
path_to_x(root.left, path, x, go)
path_to_x(root.right, path, x, go)
if go[0]:
path.pop()
path_p = []
go = [True]
path_to_x(root, path_p, p, go)
path_q = []
go[0] = True
path_to_x(root, path_q, q, go)
strt = min(len(path_p), len(path_q)) - 1
for i in range(strt, -1, -1):
if path_p[i] == path_q[i]:
return path_p[i]Last updated