Lowest Common Ancestor of a Binary Search Tree
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5recursion
# 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
"""
if not root:
return None
# 在左子树
if root.val > max(p.val,q.val):
return self.lowestCommonAncestor(root.left, p, q)
elif root.val < min(p.val, q.val):
return self.lowestCommonAncestor(root.right, p, q)
else:
return rootLast updated