一、Description
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] Output: [2,7,4] Explanation:
The output "[2, 7, 4]" is a serialization of the subtree rooted at the node with value 2.
二、Analyzation
对于该问题,开始想到的是找叶子结点的最近公共祖先,但如果最深层的结点数大于等于2就比较麻烦,所以换了一个思路:对于任何一个结点node,算出该结点所在的层数level(根结点在第0层),算出该结点所在子树的高度,与整棵树的高度,如果满足level = h - height(node),说明该结点所在的子树存在最深层的结点,则可以继续递归,反之停止递归。如果一个结点的左结点和右结点均满足上述公式,说明左右子树都包含最深结点,则返回该结点(公共祖先),这也是递归结束的条件。
三、Accepted code
class Solution {
public TreeNode subtreeWithAllDeepest(TreeNode root) {
if (root == null) {
return root;
}
int h = height(root);
return help(root, 1, h);
}
public TreeNode help(TreeNode root, int level, int h) {
int left = height(root.left);
int right = height(root.right);
if (left == h - level && right == h - level) {
return root;
} else if (left == h - level) {
return help(root.left, level + 1, h);
} else if (right == h - level) {
return help(root.right, level + 1, h);
}
return root;
}
public int height(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
int leftHeight = 0, rightHeight = 0;
if (root.left != null) {
leftHeight = height(root.left) + 1;
}
if (root.right != null) {
rightHeight = height(root.right) + 1;
}
return leftHeight > rightHeight ? leftHeight :rightHeight;
}
}