#938. Range Sum of BST
Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23
BST左节点的值>根结点的值>右节点的值。题目要求找出L和R之间的值的和。首先判断root的值是否在L和R之间,是的话就加到sum中。如果root的值大于L,则root的左子树肯定都比L小,则在root的右子树和R之间进一步搜索。如果root的值小于R则root的右子树肯定都比R小,则在root的左子树和L之间进一步搜索。
function getSum(root,L,R) {
var sum = 0;
if(root) {
if(root.val<=R && root.val>=L) {
sum=sum+root.val
}
if(root.val>L) {
sum=sum+rangeSumBST(root.left,L,R)
}
if(root.val<R) {
sum=sum+rangeSumBST(root.right,L,R)
}
}
return sum;
}
var rangeSumBST = function(root, L, R) {
return getSum(root,L,R);
};