/**
* 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) {
int answer = 0;
dfs(root, low, high, answer);
return answer;
}
private:
void dfs(TreeNode *root, int low, int high, int &answer) {
if (root == nullptr) {
return;
}
if (root->val < low) {
dfs(root->right, low, high, answer);
return;
}
if (high < root->val) {
dfs(root->left, low, high, answer);
return;
}
answer += root->val;
dfs(root->left, low, high, answer);
dfs(root->right, low, high, answer);
}
};
root
.
root
.
/**
* 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) {
return 0;
}
if (root->val < low) {
return rangeSumBST(root->right, low, high);
}
if (high < root->val) {
return rangeSumBST(root->left, low, high);
}
return root->val +
rangeSumBST(root->left, low, high) +
rangeSumBST(root->right, low, high);
}
};
root
.
root
.
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up