点开电脑里的两个文件夹,要找它们共同的最深一层目录,可以先把第一个文件的上级目录记下来,再从第二个文件开始往上翻。树上的做法也是如此。
根节点 3 的左孩子是 5,5 的一条分支下面有 4。求 5 和 4 的公共祖先时,5 本身就算祖先;从 4 上溯,第一次落到 5 的祖先集合中,就是 5。
class Solution:
def lowestCommonAncestor(self, root, p, q):
parent = {root: None}
stack = [root]
while p not in parent or q not in parent:
node = stack.pop()
for child in (node.left, node.right):
if child:
parent[child] = node
stack.append(child)
chain = set()
while p:
chain.add(p)
p = parent[p]
while q not in chain:
q = parent[q]
return q
最坏访问整棵树,时间、空间均为 O(n)。题目保证 p、q 都在树上。集合保存节点对象,调用方拿回的也是原树中的节点。

