题目链接:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p==q : return p
if not root or not q or not p : return
max_val=max(q.val,p.val)
min_val=min(q.val,p.val)
cur = root
while cur:
if cur.val > max_val and cur.val > min_val:
cur=cur.left
elif cur.val < max_val and cur.val < min_val:
cur=cur.right
else:
return cur
解题思路
主要是抓住公共祖先的性质,前提为二叉搜索树