没看答案,也适用于普通的二叉树。
# 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':
res = TreeNode(100)
# 后序遍历,由深向浅
def dfs(root):
if not root:
return False
nonlocal res
flag1 = True if root.val == p.val or root.val == q.val else False # 判断root是不是p或q
flag2 = dfs(root.left) # 判断root的左子树有没有p或q
flag3 = dfs(root.right) # 判断root的右子树有没有p或q
# 左右 or 左根 or 右根有p和q则满足答案
if flag1 + flag2 + flag3 >= 2:
res = root
return flag1 or flag2 or flag3
dfs(root)
return res
利用BST的性质,从根节点开始遍历;
- 如果当前节点的值大于 p 和 q 的值,说明 p 和 q 应该在当前节点的左子树中,因此将当前节点移动到它的左子节点;
- 如果当前节点的值小于 p 和 q 的值,说明 p 和 q 应该在当前节点的右子树中,因此将当前节点移动到它的右子节点;
- 如果当前节点的值不满足上述两条要求,那么说明当前节点就是最近公共祖先节点。此时,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':
res = root
while True:
if p.val < res.val and q.val < res.val:
res = res.left
elif p.val > res.val and q.val > res.val:
res = res.right
else:
break
return res