Smallest Subtree with all the Deepest Nodes - Problem
Given the root of a binary tree, your task is to find the smallest subtree that contains all the deepest nodes in the tree.
The depth of a node is defined as the shortest distance from the root to that node. The deepest nodes are those nodes that have the maximum depth among all nodes in the tree.
A subtree of a node consists of that node and all its descendants. You need to return the root of the smallest such subtree.
Example: If the deepest nodes are leaves at depth 3, and they have different parents, you need to find their lowest common ancestor that forms the smallest subtree containing all of them.
Input & Output
example_1.py — Python
$
Input:
root = [3,5,1,6,2,0,8,null,null,7,4]
›
Output:
[2]
💡 Note:
The deepest nodes are 7 and 4 at depth 3. The smallest subtree containing both is rooted at node 2, so we return node 2.
example_2.py — Python
$
Input:
root = [1]
›
Output:
[1]
💡 Note:
The tree has only one node, so it's both the deepest and the answer.
example_3.py — Python
$
Input:
root = [0,1,3,null,2]
›
Output:
[2]
💡 Note:
The deepest node is 2 at depth 2. The smallest subtree containing it is just node 2 itself.
Constraints
- The number of nodes in the tree will be in the range [1, 500]
- -500 ≤ Node.val ≤ 500
- The values of the nodes in the tree are unique
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code