Problem Description
Given the root of a binary tree, return the smallest subtree such that it contains all the deepest nodes in the original tree. The deepest nodes are those that have the largest distance from the root. The solution is to find the lowest common ancestor (LCA) of all deepest nodes because this node represents the smallest subtree that includes every deepest node.
Key Insights
- The deepest nodes can be found using a DFS traversal while tracking each node's depth.
- The problem can be solved by performing a DFS that returns both the candidate subtree (or LCA for deepest nodes) and the height of that subtree.
- At each node, comparing the maximum depths of its left and right subtrees helps decide:
- If left and right depths are equal, the current node is the LCA.
- Otherwise, the deeper subtree contains all the deepest nodes.
- This recursive strategy efficiently fuses the search for maximum depth and the lowest common ancestor in one traversal.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes in the tree, as we visit each node once. Space Complexity: O(h) in the recursion stack, where h is the height of the tree (O(n) in the worst-case for skewed trees).
Solution
The solution uses a depth-first search (DFS) to compute for every node the depth of its deepest descendant. As we traverse, each subtree returns both its maximum depth and the candidate node that forms the smallest subtree containing all deepest nodes. At each node:
- Recursively get the deepest node and depth for the left and right children.
- Compare these depths to determine whether the current node is the common ancestor or if one of the children already covers all deepest nodes.
- Return the candidate with the updated maximum depth.
This approach effectively combines depth calculation with the LCA determination.