-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsolution.cpp
50 lines (48 loc) · 1.36 KB
/
solution.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
/**
* 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) {
*/
/**
* 41 / 41 test cases passed.
* Runtime: 180 ms
* Memory Usage: 63.1 MB
*/
class Solution {
public:
void inorder(TreeNode* root, int low, int high, int* ans) {
if (!root) return;
inorder(root->left, low, high, ans);
if (root->val > high) return;
if (root->val >= low) *ans += root->val;
inorder(root->right, low, high, ans);
}
int rangeSumBST(TreeNode* root, int low, int high) {
int ans = 0;
inorder(root, low, high, &ans);
return ans;
}
};
/**
* 41 / 41 test cases passed.
* Runtime: 204 ms
* Memory Usage: 63.2 MB
*/
class Solution2 {
public:
int rangeSumBST(TreeNode* root, int low, int high) {
if (root == nullptr) return 0;
if (root->val > high) {
return rangeSumBST(root->left, low, high);
}
if (root->val < low ) {
return rangeSumBST(root->right, low, high);
}
return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);
}
};