Given the root of a binary tree, the depth of each node is the shortest distance to the root.
Return the smallest subtree such that it contains all the deepest nodes in the original tree.
A node is called the deepest if it has the largest depth possible among any node in the entire tree.
The subtree of a node is tree consisting of that node, plus the set of all descendants of that node.
Note: This question is the same as 1123: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4]
Output: [2,7,4]
Explanation: We return the node with value 2, colored in yellow in the diagram.
The nodes coloured in blue are the deepest nodes of the tree.
Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.
找出包含最深点的最小子树,最深点是指到root的距离最远。
思路:
可按求树的高度计算,但是返回高度的同时还要返回包含最深点的最小树的root
如果左右子树的高度相同,那么当前root就可能是最小树的root
如果左子树高度>右子树高度,那当前root就不是最小树的root,最小树在左子树上,返回时root就是左子树返回的root
因为又要返回高度,又要返回最小树的root,可以定义一个class,包含这两个成员,当然也可以返回一个Object数组,取值时用down cast
public TreeNode subtreeWithAllDeepest(TreeNode root) {
if(root == null) return null;
return (TreeNode)(height(root)[1]);
}
Object[] height(TreeNode root) {
if(root == null) {
return new Object[]{-1, root};
}
Object[] left = height(root.left);
Object[] right = height(root.right);
int leftH = ((Integer)left[0]).intValue();
int rightH = ((Integer)right[0]).intValue();
if(leftH > rightH) {
return new Object[]{leftH+1, left[1]};
} else if(leftH < rightH) {
return new Object[]{rightH+1, right[1]};
}
return new Object[]{leftH+1, root};
}