LeetCode 938. 二叉搜索树的范围和
原题链接
简单
作者:
飞呀
,
2021-05-02 23:45:10
,
所有人可见
,
阅读 288
/**
* 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*> q;
if(root != nullptr){
q.push(root);
}else{
return 0;
}
TreeNode* cur;
int sum = 0;
while(!q.empty()){
cur = q.front();
q.pop();
int tmp = cur->val;
if(tmp >= low && tmp <= high){
sum += tmp;
}
if(cur->left != nullptr){
q.push(cur->left);
}
if(cur->right != nullptr){
q.push(cur->right);
}
}
return sum;
}
};