Lowest Common Ancestor of a Binary Tree
Difficulty: Medium · Pattern: Trees & BST · LeetCode #236
Given a binary tree (not necessarily a BST) and two distinct nodes p and q in it, return their lowest common ancestor: the deepest node that has both as descendants (a node counts as its own descendant).
In the tests p and q are given by value, and your function receives the node objects. The expected output is the LCA's value.
Examples
text
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
p = 5, q = 1 → 3
p = 5, q = 4 → 5 (5 is an ancestor of 4)Hints
- Let
dfs(node)returnp,q, or the LCA if any of them lies in this subtree, andnullotherwise. - If the left call and the right call both return non-null, the current node is where the two paths meet.
Approach
Post-order recursion:
text
lca(node):
if node is null or node is p or node is q: return node
L = lca(node.left)
R = lca(node.right)
if L and R: return node # p and q are on different sides
return L or R # pass up whichever one we foundWhy does returning node early when node == p work even if q is below p? Because then p is the LCA. Nothing else in the tree will return non-null, so p bubbles all the way up.
Each node is visited once: O(n). For many queries on one tree, you'd precompute binary lifting (O(log n) per query) or Euler tour + RMQ.
Complexity
Time: O(n). Space: O(h).
Python solution
def lowestCommonAncestor(root, p, q):
if not root or root is p or root is q:
return root
L = lowestCommonAncestor(root.left, p, q)
R = lowestCommonAncestor(root.right, p, q)
if L and R:
return root
return L or RJavaScript solution
function lowestCommonAncestor(root, p, q) {
if (!root || root === p || root === q) return root;
const L = lowestCommonAncestor(root.left, p, q);
const R = lowestCommonAncestor(root.right, p, q);
if (L && R) return root;
return L || R;
}