Lowest Common Ancestor
Example
4
/ \
3 7
/ \
5 6Solution
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of the binary search tree.
@param A and B: two nodes in a Binary.
@return: Return the least common ancestor(LCA) of the two nodes.
"""
def lowestCommonAncestor(self, root, A, B):
if root == None:
return None
if root == A or root == B: #stop机制, 从上一个递归是root.left or root.right 进来的,这样无论是等于左右节点,都退出返回。
return root
left = self.lowestCommonAncestor(root.left, A, B)
right = self.lowestCommonAncestor(root.right, A, B)
if left and right:
return root
if left:
return left
if right:
return right
return NoneLast updated