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.
思路:divide conquer,递归函数表达的意义是:返回当前node的 minTreeNode,minSum,以及包含当前value的sum
拿到左边右边的minSum之后,跟ResultType.minSum进行比较,左边小更新两个值,右边小更新两个值,sum这个结果不变继续往上传;注意minSum default 设置成Integer.MAX_VALUE,这样就避免了判断leaf节点的问题,否则会有NPE;
/**
* 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 {
class ResultType {
TreeNode minRoot;
int minSum;
int sum;
public ResultType (TreeNode minRoot, int minSum, int sum) {
this.minRoot = minRoot;
this.minSum = minSum;
this.sum = sum;
}
}
/**
* @param root: the root of binary tree
* @return: the root of the minimum subtree
*/
public TreeNode findSubtree(TreeNode root) {
return divideConquer(root).minRoot;
}
public ResultType divideConquer(TreeNode root) {
if(root == null){
return new ResultType(null, Integer.MAX_VALUE, 0);
}
ResultType leftRes = divideConquer(root.left);
ResultType rightRes = divideConquer(root.right);
int totalSum = root.val + leftRes.sum + rightRes.sum;
ResultType resultType = new ResultType(root, totalSum, totalSum);
if(leftRes.minSum <= resultType.minSum) {
resultType.minRoot = leftRes.minRoot;
resultType.minSum = leftRes.minSum;
}
if(rightRes.minSum <= resultType.minSum) {
resultType.minRoot = rightRes.minRoot;
resultType.minSum = rightRes.minSum;
}
return resultType;
}
}
思路2:用traverse的思想,helper function递归函数的物理意义是:包含当前node value的总sum;但是每次traverse之后,更新global sum和node即可;取最小的。
/**
* 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
*/
int globalSum = Integer.MAX_VALUE;
TreeNode globalNode = null;
public TreeNode findSubtree(TreeNode root) {
helper(root);
return globalNode;
}
public int helper(TreeNode root) {
if(root == null) {
return 0;
}
int curSum = helper(root.left) + helper(root.right) + root.val;
if(curSum <= globalSum) {
globalNode = root;
globalSum = curSum;
}
return curSum;
}
}