Leetcode 938.二叉搜索树的范围和
原题戳这里
题解:
/**
* 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 dfs(TreeNode *r, int low, int high){
int res = 0;
if (r->val >= low && r->val <= high) res = r->val;
if (r->left != NULL) res += dfs(r->left, low, high);
if (r->right != NULL) res += dfs(r->right, low, high);
return res;
}
int rangeSumBST(TreeNode* root, int low, int high) {
int res = 0;
res = dfs(root, low, high);
return res;
}
};