/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param low int整型
* @param high int整型
* @return int整型
*/
int ans = 0;
int rangeSumBST(TreeNode* root, int low, int high) {
// write code here
dfs(root, low, high);
return ans;
}
int dfs(TreeNode* root, int low, int high) {
if (!root)return 0;
dfs(root->left, low, high);
if (root->val >= low && root->val <= high)
ans += root->val;
dfs(root->right, low, high);
return 0;
}
};
一、题目考察的知识点
二叉搜索树+中序遍历
二、题目解答方法的文字分析
二叉搜索树的中序遍历是一个递增数列,所以我们在递归的时候把在区间内的数加起来就是答案
三、本题解析所用的编程语言
c++

京公网安备 11010502036488号