难度:中等
题目描述:
思路总结:
- 递归版本 核心思想是基于经验得到的。一个节点如果根、左子树、右子树有两个为True,那么当前节点就是最近公共祖先。
- 非递归 父节点,两条路径回溯的找共同祖先。
题解一:(递归)
# 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':
#思路:没有了二叉搜索树的性质,这题似乎难了点。
#有一个思路,分别记录两条路径,找到其层级和val相同的点,但是不行,因为只能记录路径val,不能记录路径节点,最后返回的是路径节点。
ans = None
def helper(node):
if not node:
return False
left = helper(node.left)
right = helper(node.right)
mid = node.val == p.val or node.val == q.val
if mid+left+right >= 2:
nonlocal ans
ans = node
return left or right or mid
helper(root)
return ans
题解一结果:
题解二:(非递归——父节点指针)
算法:
- 遍历树,存p和q之前的父指针;
- 将p的所有祖先放到列表中;
- 遍历q的祖先,如果某一层在p的祖先列表中,返回当前祖先。
#官方解法
# 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':
#思路:非递归——父指针。遍历,存baba字典。
baba = {root:None}
stack = [root]
while p not in baba or q not in baba:
cur = stack.pop()
if cur.left:
baba[cur.left] = cur
stack.append(cur.left)
if cur.right:
baba[cur.right] = cur
stack.append(cur.right)
ppar = set()
while p:
ppar.add(p)
p = baba[p]
while q not in ppar:
q = baba[q]
return q
题解二结果: