题目描述:
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 node 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;
* }
* }
*/
class ResultType {
TreeNode node;
public int sum;
public ResultType(int sum) {
this.sum = sum;
}
}
public class Solution {
/**
* @param root the root of binary tree
* @return the root of the minimum subtree
*/
private TreeNode subtree = null;
private int subtreeSum = Integer.MAX_VALUE;
public TreeNode findSubtree(TreeNode root) {
helper(root);
return subtree;
}
private ResultType helper(TreeNode root) {
if (root == null) {
return new ResultType(0);
}
ResultType left = helper(root.left);
ResultType right = helper(root.right);
ResultType result = new ResultType(left.sum + right.sum + root.val);
//int sum = helper(root.left) + helper(root.right) + root.val;
if (result.sum < subtreeSum) {
subtreeSum = result.sum;
subtree = root;
}
return result;
}
}