Skip to content

Commit 78082ce

Browse files
committed
Add 938-RangeSumOfBST.cpp
1 parent b858c30 commit 78082ce

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
13+
void dfs(TreeNode* root, int low, int high, int &sum){
14+
if(root == nullptr){return;}
15+
if(low <= root->val && root->val <= high){sum += root->val;}
16+
dfs(root->left, low, high, sum);
17+
dfs(root->right, low, high, sum);
18+
}
19+
20+
class Solution {
21+
public:
22+
int rangeSumBST(TreeNode* root, int low, int high) {
23+
int total(0);
24+
dfs(root, low, high, total);
25+
return total;
26+
27+
}
28+
};

0 commit comments

Comments
 (0)