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;
}
}