The Lowest Common Ancestor of a Binary Tree problem gives you a generic binary tree (NOT a Binary Search Tree) and two target nodes, p and q. You must find the deepest node in the tree that has both p and q as descendants. Unlike a BST, the values in this tree are not sorted, so you cannot rely on numerical comparisons to guide your search.
This is arguably the most famous recursion problem in software engineering interviews. It perfectly evaluates a candidate's grasp of Depth-First Search (DFS) and post-order traversal. It tests your ability to bubble up boolean states or node references from the leaves of a tree back up to the root to identify a convergence point.
This problem heavily relies on Post-Order Depth-First Search (DFS). The recursive function searches the left and right subtrees.
p or q, return the current node.p was found in one branch and q in the other. The current node is the convergence point—the LCA! Return it. If only one returns non-null, pass that non-null value upwards.Imagine a tree: Root 3. Left child 5, Right child 1.
We want the LCA of 5 and 1.
3.
5. It matches p! Return node 5 upwards.1. It matches q! Return node 1 upwards.3: The left search returned 5, and the right search returned 1. Since BOTH are non-null, the current node (3) is the split point!
Root 3 returns itself. Node 3 is the LCA.If we wanted the LCA of 5 and a descendant of 5, the search down the other branch would return null, and node 5 would just bubble itself all the way to the top.
A frequent mistake is attempting to find paths to p and q from the root, storing them in arrays, and then comparing the arrays to find where they diverge. While this logically works, it takes extra space and requires multiple passes. The optimal recursive approach finds the answer in a single pass with no extra arrays, utilizing just the recursive call stack.
Memorize the 5-line recursive solution for the Lowest Common Ancestor coding pattern. It is incredibly elegant:
null, p, or q).root.| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Path Sum III | Medium | Solve | |
| Boundary of Binary Tree | Medium | Solve | |
| Distribute Coins in Binary Tree | Medium | Solve | |
| Find Leaves of Binary Tree | Medium | Solve | |
| Sum Root to Leaf Numbers | Medium | Solve |