Given a binary tree, find the subtree with minimum sum. Return the root of the subtree.
Given a binary tree:
1
/ \
-5 2
/ \ / \
0 2 -4 -5
return the node1.
/**
* 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 minSum = Integer.MAX_VALUE;
private TreeNode subtree = null;
public TreeNode findSubtree(TreeNode root) {
// write your code here
if (root == null) {
return root;
}
int ans = helper(root);
return subtree;
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int sum = root.val + helper(root.left) + helper(root.right);
if (sum < minSum) {
minSum = sum;
subtree = root;
}
return sum;
}
}