LeetCode 865. Smallest Subtree With All the Deepest Nodes
Question
Given a binary tree rooted at root
, the depth of each node is the shortest distance to the root.
A node is deepest if it has the largest depth possible among any node in the entire tree.
The subtree of a node is that node, plus the set of all descendants of that node.
Return the node with the largest depth such that it contains all the deepest nodes in its subtree.
Example
1 | Input: [3,5,1,6,2,0,8,null,null,7,4] |
Solution
- use preorder and hashmap to maintain the relationship between node and depth and keep the max depth vairable. And then use the similar postorder showed in LCA
- Or, we can build the class (which contains node and depth) and to use postorder to solve.
- if (depth(left) > depth(right)) return new data(left.node, depth + 1);
- if (depth(left) < depth(right)) return new data(right.node, depth + 1);
- Otherwise, we return root, also maintain the depth. (In this case, it shows that it have deepest tree which left depth equals right depth)
Code
1 | // two pass, time:O(n) space:O(n) |