Lowest Common Ancestor of Deepest Leaves (LeetCode 1123): Solution and Explanation
Given a binary tree, find every leaf at the greatest depth and return the deepest node whose subtree contains all of them.
Intuition
A level-order BFS visits the tree one depth at a time. The last level it reaches is exactly the set of deepest leaves, so finding them costs one pass.
All of those leaves sit at the same depth. If every one of them steps up to its parent at the same time, they stay level with each other, and two walkers that share a parent merge into one.
The first moment only one walker is left, every deepest leaf has reached the same node from below. Nothing lower contains them all, so that node is the lowest common ancestor.
Approach: BFS, then climb together
- Run a BFS one level at a time and record
parent[child] = nodefor every edge. - Stop when a level has no children. That level holds the deepest leaves.
- Put the level into a set called the frontier.
- While the frontier has more than one node, replace it with the set of their parents.
- Return the single node left in the frontier.
Step-by-step example
root = [3,5,1,6,2,0,8,null,null,7,4]
- BFS levels: [3], then [5,1], then [6,2,0,8], then [7,4]. Level [7,4] has no children, so it is the last one.
- Frontier = {7, 4}. Two nodes, so climb.
- Both have parent 2, so the frontier becomes {2}.
- One node left: return node 2, whose subtree serializes to [2,7,4].
Code: Python, Java, C++
1class Solution:
2 def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
3 parent = {root: None}
4 level = [root]
5 while True:
6 nxt = []
7 for node in level:
8 for child in (node.left, node.right):
9 if child:
10 parent[child] = node
11 nxt.append(child)
12 if not nxt:
13 break
14 level = nxt
15 frontier = set(level)
16 while len(frontier) > 1:
17 frontier = {parent[node] for node in frontier}
18 return frontier.pop()1class Solution {
2 public TreeNode lcaDeepestLeaves(TreeNode root) {
3 Map<TreeNode, TreeNode> parent = new HashMap<>();
4 List<TreeNode> level = new ArrayList<>();
5 level.add(root);
6 while (true) {
7 List<TreeNode> next = new ArrayList<>();
8 for (TreeNode node : level) {
9 for (TreeNode child : new TreeNode[]{node.left, node.right}) {
10 if (child != null) {
11 parent.put(child, node);
12 next.add(child);
13 }
14 }
15 }
16 if (next.isEmpty()) break;
17 level = next;
18 }
19 Set<TreeNode> frontier = new HashSet<>(level);
20 while (frontier.size() > 1) {
21 Set<TreeNode> up = new HashSet<>();
22 for (TreeNode node : frontier) up.add(parent.get(node));
23 frontier = up;
24 }
25 return frontier.iterator().next();
26 }
27}1class Solution {
2public:
3 TreeNode* lcaDeepestLeaves(TreeNode* root) {
4 unordered_map<TreeNode*, TreeNode*> parent;
5 vector<TreeNode*> level = {root};
6 while (true) {
7 vector<TreeNode*> next;
8 for (TreeNode* node : level) {
9 for (TreeNode* child : {node->left, node->right}) {
10 if (child) {
11 parent[child] = node;
12 next.push_back(child);
13 }
14 }
15 }
16 if (next.empty()) break;
17 level = next;
18 }
19 unordered_set<TreeNode*> frontier(level.begin(), level.end());
20 while (frontier.size() > 1) {
21 unordered_set<TreeNode*> up;
22 for (TreeNode* node : frontier) up.insert(parent[node]);
23 frontier = up;
24 }
25 return *frontier.begin();
26 }
27};Time and space complexity
O(n)
The BFS touches each node once, and the climb visits each ancestor at most once per level.
O(n)
The parent map stores one entry per node.
Other approaches
Post-order depth pairs (time O(n), space O(h))
Return (depth, lca) from each subtree. If both sides have the same depth the current node is the answer, otherwise pass up the deeper side's answer. One pass, no parent map.
Height at every node (time O(n^2), space O(h))
Start at the root and step into whichever child has the greater height until both heights are equal. Recomputing heights makes it quadratic unless memoized.
Common mistakes
- Taking the LCA of all leaves instead of only the deepest ones. Shallow leaves must be ignored.
- Climbing the walkers one at a time instead of all together. They only meet at the right node when they move in step.
- Forgetting the single deepest leaf case. When there is one, it is its own lowest common ancestor and must be returned directly.
Frequently asked questions
Is this the same problem as LeetCode 865?
Yes. Smallest Subtree with all the Deepest Nodes asks for the same node, because the smallest subtree holding all deepest nodes is rooted at their lowest common ancestor.
Why does a set work for the frontier?
Two walkers with the same parent become the same node after a climb. The set merges them automatically, so its size drops exactly when branches join.
What does the answer look like?
It is a tree node. The judge compares the level-order serialization of the subtree rooted at that node.