题解一:(递归)
# 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
#官方解法
# 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