938. Range Sum of BST
思路:
要弄清楚题目的意思,返回大小在[low,high]的数的大小的和,不是树里在这个范围里面的节点的和。
那么就是树的遍历
DFS,BFS两种完成。
因为是二叉搜索树,我们有如下几种情况:
- 遍历到了空节点,返回0.
- 该节点大于high,那么就进入该节点的左子树找更小的数。
- 该节点小于low,那么进入该节点的右子树找更小的树。
- 如果节点的大小在[low,right]之间,那么我们就把该节点的val+其左子树返回的指和右子树返回的值即可。
代码:
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) return rangeSumBST(root->right,low,high);
if(root->val>high) return rangeSumBST(root->left,low,high);
return root->val+rangeSumBST(root->left,low,high)+rangeSumBST(root->right,low,high);
}
};
DFS迭代:
BFS迭代:
/**
* 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;
int res=0;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
TreeNode* temp = q.front();
q.pop();
if(temp->left&&temp->val>high) q.push(temp->left);
if(temp->right&&temp->val<low) q.push(temp->right);
if(temp->val>=low&&temp->val<=high) {
if(temp->left) q.push(temp->left);
if(temp->right) q.push(temp->right);
res+=temp->val;
}
}
return res;
}
};

浙公网安备 33010602011771号