Find the smallest subtree that contains every node at the maximum depth of a binary tree.
Given the root of a binary tree, return the root node of the smallest subtree that contains all of the tree's deepest nodes.
A node is considered deepest if its depth from the root is maximal among all nodes in the tree. If there is only one deepest node, the answer is that node itself.
The returned subtree must include every deepest node, and among all such subtrees, it should be the one rooted as low as possible in the tree.
The key is to compare the deepest depth in the left and right subtrees. The answer is:
Example 1
Input
root = [3,5,1,6,2,0,8,null,null,7,4]
Output
[2,7,4]
Explanation
The deepest nodes are 7 and 4, both at the same maximum depth. The smallest subtree containing both is rooted at 2.
Example 2
Input
root = [1]
Output
[1]
Explanation
There is only one node, so it is also the deepest node and the answer.
Example 3
Input
root = [1,2,3,4]
Output
[4]
Explanation
Node 4 is the only deepest node, so the smallest subtree is the node itself.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.