cpp: add “938. Range Sum of BST”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
20632b1d7c
commit
30202920b0
1 changed files with 28 additions and 0 deletions
28
cpp/range-sum-of-bst.cpp
Normal file
28
cpp/range-sum-of-bst.cpp
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
/**
|
||||||
|
* 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) {}
|
||||||
|
* };
|
||||||
|
*/
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
int rangeSumBST(TreeNode *root, int low, int high) {
|
||||||
|
if (root == nullptr) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int currentValue = 0;
|
||||||
|
if (low <= root->val && root->val <= high) {
|
||||||
|
currentValue = root->val;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (currentValue + rangeSumBST(root->left, low, high) +
|
||||||
|
rangeSumBST(root->right, low, high));
|
||||||
|
}
|
||||||
|
};
|
Loading…
Reference in a new issue