I was looking at minimum sum subtree problem and came up with recursion solution:
public class Solution {
/**
* @param root: the root of binary tree
* @return: the root of the minimum subtree
*/
int minSoFar;
public TreeNode findSubtree(TreeNode root) {
TreeNode minNode = root;
minSoFar = Integer.MAX_VALUE;
subtreeSum(root,minNode);
return minNode;
}
//return sum of the tree at root
private int subtreeSum(TreeNode root, TreeNode minNode){
if(root == null){
return 0;
}
int sum = root.val + subtreeSum(root.left,minNode) + subtreeSum(root.right,minNode);
if(sum < minSoFar){
minNode = root;
minSoFar = sum;
}
return sum;
}
}
However the minNode does not get updated during the recursive calls, what is the reason for that? if I change minNode to a global variable it would work. I couldn't figure out where went wrong.