In the Lowest Common Ancestor of Deepest Leaves problem, you are given a binary tree. Your goal is to find the lowest common ancestor of all the nodes that are at the maximum depth of the tree. The deepest leaves are the nodes furthest away from the root.
This problem is a fantastic blend of two distinct tree concepts: calculating depth and finding ancestors. Interviewers ask it because it forces candidates to evaluate paths dynamically. You cannot find the LCA until you know what the maximum depth is, so you must write code that either does two passes or smartly combines depth-checking with LCA-bubbling in a single pass.
The most optimal solution uses a Single Pass Depth-First Search (DFS) that returns a tuple or pair. The recursive function returns two pieces of information: (Current_Subtree_Depth, LCA_Node_For_This_Subtree).
At any node, you look at the results from the left child and right child.
left_depth == right_depth: The deepest leaves are split between both sides. The current node is the LCA! You return (left_depth + 1, current_node).left_depth > right_depth: The deepest leaves are only on the left. The LCA must be whatever the left child returned. You return (left_depth + 1, left_LCA).right_depth > left_depth: Return (right_depth + 1, right_LCA).Tree: root 1, left 2, right 3. 2 has left 4.
We want the LCA of the deepest leaves. Deepest leaf is just 4.
4: left depth 0, right depth 0. Returns (1, node 4).2: left returned (1, node 4). Right is null, returns (0, null). Left depth (1) > Right depth (0). Returns (2, node 4).3: left/right null. Returns (1, node 3).1: left returned (2, node 4). Right returned (1, node 3). Left depth (2) > Right depth (1). Root 1 ignores the right side entirely and passes up the left side's LCA. Returns (3, node 4).
The final LCA is node 4.Candidates often resort to a two-pass solution: a BFS to find the maximum depth and collect all the deepest leaves, followed by another traversal to find the LCA of that list. While functional, it is bulky and slow. Furthermore, trying to use global variables to track max depth during a single pass can lead to messy state management and bugs if not handled perfectly.
To master the Lowest Common Ancestor of Deepest Leaves interview pattern, get comfortable returning custom Objects or Tuples from your recursive functions. If your recursive function can simultaneously pass up the "score" (depth) and the "winner" (the LCA node), you can solve almost any complex tree aggregation problem in a single elegant sweep.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Clone Binary Tree With Random Pointer | Medium | Solve | |
| Cousins in Binary Tree II | Medium | Solve | |
| Correct a Binary Tree | Medium | Solve | |
| All Nodes Distance K in Binary Tree | Medium | Solve | |
| Find Distance in a Binary Tree | Medium | Solve |