给一棵二叉树, 找到和为最小的子树, 返回其根节点。
样例
例1:
输入:
1
/ \
-5 2
/ \ / \
0 2 -4 -5
输出:1
例2:
输入:
1
输出:1
注意事项
LintCode会打印根节点为你返回节点的子树。保证只有一棵和最小的子树并且给出的二叉树不是一棵空树。
解题思路1:
采用全局变量记录最小和值以及最小和对应的根节点,然后递归求和判断即可。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
private TreeNode res;
private int minSum = Integer.MAX_VALUE;
/**
* @param root: the root of binary tree
* @return: the root of the minimum subtree
*/
public TreeNode findSubtree(TreeNode root) {
// write your code here
helper(root);
return res;
}
private int helper(TreeNode root){
if(root == null)
return 0;
int sum = helper(root.left) + helper(root.right) + root.val;
if(sum <= minSum){
minSum = sum;
res = root;
}
return sum;
}
}