剑指 Offer 68. 二叉搜索树/一般树的最近公共祖先
二叉搜索树的最近公共祖先
# 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.val > q.val: p, q = q, p # 保证 p.val < q.val
while root:
if root.val < p.val: # p,q 都在 root 的右子树中
root = root.right # 遍历至右子节点
elif root.val > q.val: # p,q 都在 root 的左子树中
root = root.left # 遍历至左子节点
else: break
return root
# 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.val > q.val: p, q = q, p
if not root or p.val <= root.val and q.val >= root.val:
return root
if p.val <= root.val:
return self.lowestCommonAncestor(root.left,p,q)
return self.lowestCommonAncestor(root.right,p,q)
二叉搜索树的最近公共祖先
# 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 not root or root.val == p.val or root.val == q.val:
return root
l = self.lowestCommonAncestor(root.left,p,q)
r = self.lowestCommonAncestor(root.right,p,q)
if not l:
return r
if not r:
return l
return root
后序遍历二叉树,每次返回找到的节点或空节点,从下往上传上去,若左右子节点有一个为空,则返回另一个,若都不为空,说明当前节点为最近公共祖先。因为值唯一,所以最后传上去的就是答案。左右值没相遇时只有值所在分支不为空,相遇后只有一个分支不为空且值为最近公共祖先