Given a binary tree, find the subtree with minimum sum. Return the root of the subtree.
Example
Example 1:
Input:
{1,-5,2,1,2,-4,-5}
Output:1
Explanation:
The tree is look like this:
1
/
-5 2
/ /
1 2 -4 -5
The sum of whole tree is minimum, so return the root.
Example 2:
Input: {1} Output:1 Explanation: The tree is look like this: 1 There is one and only one subtree in the tree. So we return 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 { /** * @param root: the root of binary tree * @return: the root of the minimum subtree */ private TreeNode res = null; private int globalMin = Integer.MAX_VALUE; public TreeNode findSubtree(TreeNode root) { // write your code here helper(root); return res; } private int helper(TreeNode root) { if (root == null) { return 0; } int left = helper(root.left); int right = helper(root.right); if (left + right + root.val < globalMin) { globalMin = left + right + root.val; res = root; } return left + right + root.val; } }