给定二叉搜索树的根结点 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
。
递归或者迭代
方法1:
/**
* 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:
int sum(TreeNode* root, int L, int R) {
int isum=0;
if(root==NULL) return 0;
int vv=root->val;
if(vv>=L&&vv<=R) {
isum+=sum(root->left,L,R);
isum+=sum(root->right,L,R);
isum+=vv;
} else if(vv<L) {
isum+=sum(root->right,L,R);
} else if(vv>R) {
isum+=sum(root->left,L,R);
}
return(isum);
}
int rangeSumBST(TreeNode* root, int L, int R) {
return sum(root,L,R);
}
};
方法2:
/**
* 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:
int sum(TreeNode* root, int L, int R) {
int isum=0;
queue<TreeNode*> vt;
TreeNode*p= root;
if(p==NULL) return 0;
vt.push(p);
while(!vt.empty()) {
p=vt.front();
vt.pop();
int vv=p->val;
if(vv>=L&&vv<=R) {
isum+vv;
if(p->left!=NULL) vt.push(p->left);
if(p->right!=NULL) vt.push(p->right);
} else if(vv<L) {
if(p->right!=NULL) vt.push(p->right);
} else if(vv>R) {
if(p->left!=NULL) vt.push(p->left);
}
}
return(isum);
}
int rangeSumBST(TreeNode* root, int L, int R) {
return sum(root,L,R);
}
};