Lowest Common Ancestor of a Binary Tree
Master this topic with zero to advance depth.
Lowest Common Ancestor of a Binary Tree
Find LCA.
Level I: Brute Force (Recursive Containment Check)
Intuition
The Lowest Common Ancestor (LCA) is the node where p and q first reside in different subtrees (one in left, one in right), or the node itself is one of p or q. A brute force approach checks for every node if it contains p and q in its subtrees.
Thought Process
- Define
contains(node, target)helper. - For current
root, ifrootisporq, it might be LCA. - If
contains(root.left, p & q)is true, move to left child. - If
contains(root.right, p & q)is true, move to right child. - If they are split,
rootis LCA.
Detailed Dry Run
| Node | Left contains p, q? | Right contains p, q? | Decision |
|---|---|---|---|
| 3 | no | no | Split! 3 is LCA |
Level II: Iterative with Parent Map
Intuition
We can traverse the tree and store each node's parent in a hash map. Once we've found both nodes p and q, we can backtrack from p to the root, storing all ancestors in a set. Then, we backtrack from q the first ancestor that exists in that set is the LCA.
Logic
- BFS/DFS to build
parentMapuntil bothpandqare found. - Collect all ancestors of
pin a set. - Pull upwards from
quntil an ancestor exists inp's ancestor set.
Detailed Dry Run
p=5, q=1. parents={5:3, 1:3, 3:null}. p-ancestors={5, 3}. q's parent 3 is in set -> LCA=3.
Level III: Optimal (Post-order Recursion)
Intuition
Thought Process
Instead of checking containment repeatedly, we can do a single bottom-up traversal. We ask each child: "Do you see p or q?".
Logic
- If a subtree returns a non-null node, it means
porqwas found in that subtree. - If both subtrees return non-null, the current node is the Lowest Common Ancestor.
- If only one subtree is non-null, pass that result up.
Pattern
Bottom-Up DFS: Aggregate information from children to decide for the parent.
Detailed Dry Run
| Node | Left Result | Right Result | Pass Up |
|---|---|---|---|
| 5 | p | null | p |
| 1 | null | q | q |
| 3 | 5(p) | 1(q) | 3 (LCA) |
⚠️ Common Pitfalls & Tips
This approach assumes both p and q exist in the tree. If they might not exist, a double-check pass is required.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.