So I need to sum up all nodes in a BST within an inclusive range. For example, if the range is [7, 15] ('[' and ']' mean inclusive) for the example below,
10
/ \
5 15
/ \ \
3 7 18
the sum would be 7 + 10 + 15 = 32
Here is my code below, I am doing a simple inOrderTraversal, but for some reason the resulting sum is 0.
class Solution {
public int rangeSumBST(TreeNode root, int low, int high) {
int sum = 0;
helper(root, low, high, sum);
return sum;
}
public void helper(TreeNode root, int low, int high, int sum) {
if(root != null) {
helper(root.left, low, high, sum);
if(root.val >= low && root.val <= high) {
System.out.println("sum before was " + sum);
sum = sum + root.val;
System.out.println("sum after was " + sum);
}
helper(root.right, low, high, sum);
}
}
}
Does anyone know why it is 0?