NeetCode #419LC-236MediumTrees
← Back to All Problems#419 · #236 · Lowest Common Ancestor of a Binary Tree(二叉树的最近公共祖先)
📌 Problem Statement & Constraints
Given a binary tree and two nodes
p and q, return their lowest common ancestor: the deepest node that has both as descendants (a node may be a descendant of itself). Constraints: the number of nodes is in [2, 10^5], all values are distinct, both nodes exist.💡 Core Algorithmic Approaches
- Recurse bottom-up. If the current node is
porq, return it immediately -- the answer is at or above this point. - Otherwise recurse into both children.
- If both children return a non-null result,
pandqlie in different subtrees, so the current node is the LCA. - If only one side is non-null, propagate it upward; that side already contains both nodes (or the LCA).
💻 Benchmark Python3 Implementation
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root or root is p or root is q:
return root # found one of the targets, or a leaf
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root # p and q split here -> this is the LCA
return left or right # both are on one side
# Parent-pointer variant, if each node has a `parent` attribute
class Solution2:
def lowestCommonAncestor(self, p: "Node", q: "Node") -> "Node":
a, b = p, q
while a is not b:
a = a.parent if a.parent else q # switch to the other chain at the top
b = b.parent if b.parent else p
return a⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n) for the tree version, O(h) for the parent-pointer version.
💾 Space Complexity
O(h) for the recursion stack; O(1) for the parent-pointer version.
⚠️ Interview Pitfalls & Follow-ups
- Comparing values instead of node identity:
root is pis required, since values are unique but identity is the direct test. - Returning as soon as one side is non-null without checking the other: both children must be examined to detect the split.
- Assuming
pandqare never ancestors of each other: the early return handles that case correctly. - Using the BST-specific algorithm: this tree has no ordering, so the general recursion is needed.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Trees Problems
中文速览与面试要点
二叉树的最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。百度百科中最近公共祖先的定义为:「对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。」约束:树中节点数目在范围 [2, 10^5] 内;-10^9 ≤ Node.val ≤ 10^9;所有 Node.val 互不相同;p != q;p 和 q 均存在于给定的二叉树中。
核心要点
- 后序遍历自底向上(标准解) :递归函数返回「在以当前节点为根的子树中,p 或 q 是否出现;若两者的 LCA 已确定则返回该 LCA」。
- 判断逻辑 :① 若当前节点是 p 或 q,返回当前节点;② 递归左右子树;③ 若左右子树都返回了非空结果,说明 p、q 分居两侧,当前节点即 LCA;④ 否则返回非空的那一侧。
- 为什么这个逻辑正确 :自底向上第一次「汇合」的节点必然是深度最大的公共祖先。
- 复杂度 :O(n) 时间、O(h) 空间。
常见陷阱
- 用 == 比较节点值而非 is 比较对象 :题目保证值互不相同,用值比较也能通过,但用对象身份更严谨。
- 忘记 not root 的终止条件 :会无限递归。
- 「分居两侧」的判断写成 if left or right :那是「找到任意一个」;必须 left and right 才表示分居两侧。
- 递归深度过大 :n 可达 10^5,链状树会栈溢出,需 sys.setrecursionlimit 或改迭代。
参考实现
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root or root is p or root is q:
return root # 命中 p/q 或到达空节点
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root # p、q 分居两侧 -> 当前节点即 LCA
return left or right # 返回非空的一侧