直接暴力递归
/**
* 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;
int t = root->val;
return t * (t >= low && t <= high) + rangeSumBST(root->left , low , high) + rangeSumBST(root->right , low , high);
}
};
加一点小优化
/**
* 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;
int t = root->val;
if(t < low) return rangeSumBST(root->right , low , high);//若当前值小于规定的最小值,只能遍历右子树
else if(t > high) return rangeSumBST(root->left , low , high);//若当前值大于规定最大值,只能遍历左子树
else return t + rangeSumBST(root->left , low , high) + rangeSumBST(root->right , low , high);//否则两边都得遍历
}
};