Given a binary tree, find the subtree with minimum sum. Return the root of the subtree.
traverse + divide & conquer
public class Solution {
/**
* @param root the root of binary tree
* @return the root of the minimum subtree
*/
TreeNode node = null;
int min = Integer.MAX_VALUE;
public TreeNode findSubtree(TreeNode root) {
helper(root);
return node;
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int left = helper(root.left);
int right = helper(root.right);
int sum = left + right + root.val;
if (sum < min) {
min = sum;
node = root;
}
return sum;
}
}