minimum subtree

来源:互联网 发布:音乐间谍类似软件 编辑:程序博客网 时间:2024/05/16 09:04

Given a binary tree, find the subtree with minimum sum. Return the root of the subtree.

/** * 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 {    /**     * @param root the root of binary tree     * @return the root of the minimum subtree     */    private int sum = Integer.MAX_VALUE;    private TreeNode node = null;    public TreeNode findSubtree(TreeNode root) {        // Write your code here        if (root == null) {            return node;        }        findSum(root);        return node;    }    public int findSum(TreeNode root) {        if (root == null) {            return 0;        }        int left = findSum(root.left);        int right = findSum(root.right);        int summary = root.val + left + right;        if (summary < sum) {            sum = summary;            node = root;        }        return summary;    }}