Problem Description
Given the root of a binary tree, find and return the lowest common ancestor (LCA) of its deepest leaves. The deepest leaves are the nodes with the maximum depth from the root. The LCA is defined as the deepest node that is an ancestor of all the deepest leaves.
Key Insights
- Use a post-order DFS traversal to compute the depth of subtrees.
- For each node, compare the maximum depths of the left and right subtrees.
- If both subtrees have the same maximum depth, the current node is the LCA.
- If one side is deeper, the LCA is in that subtree.
Space and Time Complexity
Time Complexity: O(N) where N is the number of nodes, as every node is visited once. Space Complexity: O(H) where H is the height of the tree, due to the recursion stack.
Solution
We solve the problem using a recursive DFS approach. For every node, we compute two pieces of information:
- The deepest depth in its subtree.
- The LCA for the deepest leaves in that subtree.
The function works in post-order:
- If a node is null, it returns a depth of 0.
- For non-null nodes, recursively compute the deepest depth and LCA from both left and right subtrees.
- Compare the depths:
- If left depth is greater, propagate the left LCA.
- If right depth is greater, propagate the right LCA.
- If both are equal, the current node is the LCA.
This way, when we backtrack to the root, we have the LCA for all the deepest leaves.