-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrange_sum_of_bst.cpp
52 lines (50 loc) · 1.49 KB
/
range_sum_of_bst.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// Without pruning (more performant?)
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
// Base case
if (root == NULL) {
return 0;
}
// Recursive without pruning
if (root->val >= L && root->val <= R) {
return root->val + rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);
}
return rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);
}
};
// With pruning
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
// Base case
if (root == NULL) {
return 0;
}
// Recursive
if (root->val >= L && root->val <= R) {
return root->val + rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);
}
// Prune left subtree
if (root->val < L) {
return rangeSumBST(root->right, L, R);
}
// Prune right subtree
if (root->val > R) {
return rangeSumBST(root->left, L, R);
}
// Default
return rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R);
}
};