938. Range Sum of BST

题目:

Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].

 

Example 1:

938. Range Sum of BST

Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32

Example 2:

938. Range Sum of BST

Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23

 

Constraints:

  • The number of nodes in the tree is in the range [1, 2 * 104].
  • 1 <= Node.val <= 105
  • 1 <= low <= high <= 105
  • All Node.val are unique.

 

思路:

用一个类成员变量sum记录总和大小,遍历整棵树,对每个node的值做判断,如果是空node,返回0,否则如果落在区间则加在sum上,往下延申并返回sum。这里事实上只用了最后一个sum,即root的那个,其他的返回sum并没有被调用到。

 

代码:

class Solution {
public:
    int rangeSumBST(TreeNode* root, int low, int high) {
        if(!root)
            return 0;
        if(root->val>=low&&root->val<=high)
            sum+=root->val;
        rangeSumBST(root->left,low,high);
        rangeSumBST(root->right,low,high);
        return sum;
    }
private:
    int sum=0;
};