最小子树之和

给一棵二叉树, 找到和为最小的子树, 返回其根节点。输入输出数据范围都在int内。

样例
样例 1:

输入:
{1,-5,2,1,2,-4,-5}
输出:1
说明
这棵树如下所示:
1
/
-5 2
/ \ /
1 2 -4 -5
整颗树的和是最小的,所以返回根节点1.

public class Solution {
    /**
     * @param root: the root of binary tree
     * @return: the root of the minimum subtree
     */

private TreeNode subtree = null;
    private int subtreeSum = Integer.MAX_VALUE;
    /**
     * @param root the root of binary tree
     * @return the root of the minimum subtree
     */
    public TreeNode findSubtree(TreeNode root) {
        helper(root);
        return subtree;
    }
    
    private int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int sum = helper(root.left) + helper(root.right) + root.val;
        if (sum <= subtreeSum) {
            subtreeSum = sum;
            subtree = root;
        }
        return sum;
    }
}

版权声明:本文为bigbig1984原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。