30 Day Challenge Day 20 | Leetcode 938. Range Sum of BST
题解
Easy
Recursion
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if(!root) return 0;
if(root->val < L) return rangeSumBST(root->right, L, R);
if(root->val > R) return rangeSumBST(root->left, L, R);
return root->val + rangeSumBST(root->left, L, root->val) + rangeSumBST(root->right, root->val, R);
}
};
DFS
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
int sum = 0;
dfs(root, L, R, sum);
return sum;
}
void dfs(TreeNode* node, int L, int R, int& sum) {
if(!node) return;
if(node->val >= L && node->val <= R) {
sum += node->val;
dfs(node->right, L, R, sum);
dfs(node->left, L, R, sum);
}
if(node->val < L) dfs(node->right, L, R, sum);
if(node->val > R) dfs(node->left, L, R, sum);
}
};