865. Smallest Subtree with all the Deepest Nodes
Problem:
Very similar to LCA. Use post order divide and conquer approach. Depth is the standard to decide return. Use a result object to wrap depth and result to avoid two pass.
Solution:
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] Output: [2,7,4] Explanation: We return the node with value 2, colored in yellow in the diagram. The nodes colored in blue are the deepest nodes of the tree. The input "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" is a serialization of the given tree. The output "[2, 7, 4]" is a serialization of the subtree rooted at the node with value 2. Both the input and output have TreeNode type.Analysis:
Very similar to LCA. Use post order divide and conquer approach. Depth is the standard to decide return. Use a result object to wrap depth and result to avoid two pass.
Solution:
class Solution {
public TreeNode subtreeWithAllDeepest(TreeNode root) {
TreeNode result = null;
return depth(root).node;
}
private Result depth(TreeNode root) {
if (root == null)
return new Result(null, 0);
Result left = depth(root.left);
Result right = depth(root.right);
if (left.depth == right.depth)
return new Result(root, left.depth + 1);
else if (left.depth > right.depth)
return new Result(left.node, left.depth + 1);
else
return new Result(right.node, right.depth + 1);
}
class Result {
int depth;
TreeNode node;
public Result(TreeNode node, int depth) {
this.depth = depth;
this.node = node;
}
}
}
评论
发表评论