一、题目
给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32
二、解法
2.1 dfs深度优先搜索
思路是用递归
/**
* 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==nullptr) return 0;
if(root->val<low){
if(root->right==nullptr) return 0;
else{
return rangeSumBST(root->right,low,high);
}
}else if(root->val>high){
if(root->left==nullptr) return 0;
else{
return rangeSumBST(root->left,low,high);
}
}else return rangeSumBST(root->left,low,high)+rangeSumBST(root->right,low,high)+root->val;
}
};
2.2 bfs广度优先搜索
思路是用一个队列保存节点,每次将队首元素出队,并检查其范围。如果是空指针,则continue。否则根据二叉搜索树的范围将相应的左右指针入队。
/**
* 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) {
queue<TreeNode*> que;
que.push(root);
int sum=0;
while(!que.empty()){
TreeNode* node=que.front();
que.pop();
if(node==nullptr) continue;
if(node->val<low){
que.push(node->right);
}else if(node->val>high){
que.push(node->left);
}else{
sum+=node->val;
que.push(node->left);
que.push(node->right);
}
}
return sum;
}
};