0%

938. Range Sum of BST

O(n) time

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if (!root) return 0;
int res = L <= root->val && root->val <= R ? root->val : 0;
if (root->val > L) { // 必须是大于L
res += rangeSumBST(root->left, L, R);
}
if (root->val < R) {
res += rangeSumBST(root->right, L, R);
}
return res;
}
};