-
Notifications
You must be signed in to change notification settings - Fork 0
/
0938. Range Sum of BST.cpp
56 lines (46 loc) · 1.23 KB
/
0938. 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
53
54
55
very simple solution
1. find nums array using inorder
2. store values in sum from low to high
3. return sum
class Solution {
void inorder(TreeNode *root, vector<int> &nums) {
if(root == NULL)
return;
inorder(root->left, nums);
nums.push_back(root->val);
inorder(root->right, nums);
}
public:
int rangeSumBST(TreeNode* root, int low, int high) {
int sum = 0;
vector<int> nums;
inorder(root, nums);
int n = nums.size();
for (int i = 0; i < n; i++) {
if(nums[i] >= low && nums[i] <= high) {
sum += nums[i];
}
}
return sum;
}
};
but we can improve this solution further without using loop the efficent solution can be like give below
this solution is used constant space
class Solution {
public:
int sum=0;
int inorder(TreeNode* root,int L,int R)
{
if(root){
inorder(root->left,L,R);
if(root->val>=L && root->val<=R)
sum+=root->val;
inorder(root->right,L,R);
}
return sum;
}
int rangeSumBST(TreeNode* root, int L, int R) {
if(!root)return 0;
return inorder(root,L,R);
}
};