596.Minimum Subtree
1.Description(Easy)
Given a binary tree, find the subtree with minimum sum. Return the root of the subtree.
Example
Given a binary tree:
1
/ \
-5 2
/ \ / \
0 2 -4 -5
return the node1
.
2.Code
与597 Subtree with maximum average 相似,
两个类变量 TreeNode 记录当前变量,minsum记录变化的最小值
public TreeNode node=null;
public int minsum=Integer.MAX_VALUE;
public TreeNode findSubtree(TreeNode root){
helper(root);
return node;
}
public int helper(TreeNode root){
if(root==null){
return 0;
}
int left=helper(root.left);
int right=helper(root.right);
int sum=root.val+left+right;
if(sum<minsum){
minsum=sum;
node=root;
}
return sum;
}
Last updated
Was this helpful?