https://leetcode-cn.com/problems/range-sum-of-bst/
思路:简单题就不多说了,遍历整棵树计算即可。dfs\bfs都行,考虑效率的话可以加一些剪枝。
/**
* 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* root,int low,int high)
{
if(!root)
return 0;
int sum=0;
if(root->val<low)
sum=dfs(root->right,low,high);
else if(root->val>high)
sum=dfs(root->left,low,high);
else
sum=dfs(root->left,low,high)+dfs(root->right,low,high)+root->val;
return sum;
}
int rangeSumBST(TreeNode* root, int low, int high) {
return dfs(root,low,high);
}
};