题目
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.
答案
class Solution {
public TreeNode subtreeWithAllDeepest(TreeNode root) {
int left = depth(root.left);
int right = depth(root.right);
if(left == right) return root;
else if(left < right) return subtreeWithAllDeepest(root.right);
else return subtreeWithAllDeepest(root.left);
}
public int depth(TreeNode root) {
if(root == null) return 0;
return Math.max(depth(root.left) + 1, depth(root.right) + 1);
}
}