题目描述:
给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。
二叉搜索树保证具有唯一的值。
示例 1:
输入:root = [10,5,15,3,7,null,18], L = 7, R = 15
输出:32
示例 2:
输入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
输出:23
提示:
树中的结点数量最多为 10000 个。
最终的答案保证小于 2^31。
思想:中序遍历,将节点值存入vector中,vector是顺序存放叶子节点数值的。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void inorder(TreeNode* root,vector<int> &res){
if(root==NULL)
return ;
inorder(root->left,res);
res.push_back(root->val);
inorder(root->right,res);
}
int rangeSumBST(TreeNode* root, int L, int R) {
vector<int> res;
inorder(root,res);
int sum=0;
for(int i=0;i<res.size();i++){
if(res[i]>=L&&res[i]<=R)
sum+=res[i];
}
return sum;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void inorder(TreeNode* root,int &sum,int &L,int &R){
if(root==NULL)
return ;
inorder(root->left,sum,L,R);
if(root->val>=L&&root->val<=R)
sum+=root->val;
inorder(root->right,sum,L,R);
}
int rangeSumBST(TreeNode* root, int L, int R) {
int sum=0;
inorder(root,sum,L,R);
return sum;
}
};
再贴一个网友的代码
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if(!root) return 0;
if(root->val >= L && root->val <= R){
return root->val + rangeSumBST(root->left,L,R) + rangeSumBST(root->right,L,R);
}else if(root->val < L){
return rangeSumBST(root->right,L,R);
}else {
return rangeSumBST(root->left,L,R);
}
}
};