题目
给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
示例1
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32
题解
1.递归
class Solution {
public:
int rangeSumBST(TreeNode* root, int low, int high) {
if (!root) return 0;
int sum = 0;
sum += rangeSumBST(root->left, low, high);
if (root->val >= low && root->val <= high) sum += root->val;
sum += rangeSumBST(root->right, low, high);
return sum;
}
};
2.非递归
class Solution {
public:
int rangeSumBST(TreeNode* root, int low, int high) {
if (!root) return 0;
queue<TreeNode*> q;
TreeNode* p = root;
int sum = 0;
while (p || q.size()) {
while (p) {
q.push(p);
p = p->left;
}
if (q.size()) {
p = q.front();
q.pop();
if (p->val >= low && p->val <= high) {
sum += p->val;
}
p = p->right;
}
}
return sum;
}
};