LintCode Minimum Subtree java solution

来源:互联网 发布:chart.js 饼图 编辑:程序博客网 时间:2024/06/06 03:04

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

Notice

LintCode will print the subtree which root is your return node.
It’s guaranteed that there is only one subtree with minimum sum and the given binary tree is not an empty tree.

Have you met this question in a real interview? Yes
Example
Given a binary tree:

 1

/ \
-5 2
/ \ / \
0 2 -4 -5
return the node 1.

使用trenversal 和 divide conquer 的方式进行处理

/** * 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     */    int sumSubtree = Integer.MAX_VALUE;    TreeNode node = null;    public TreeNode findSubtree(TreeNode root) {        // Write your code here        // using tranversal and divide conquer to finish        utiltranversal(root);        return node;    }    private int utiltranversal(TreeNode root) {        if (root == null) {            return 0;        }        int sum = utiltranversal(root.left) + utiltranversal(root.right) + root.val;        if (sum < sumSubtree) {            sumSubtree = sum;            node = root;        }        return sum;    }}
0 0