题目链接:添加链接描述
题目:
给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
示例 1:
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32
思路:
遍历整个树,将满足条件的节点值相加,遍历过程无脑使用栈。
初始时将根节点放入栈中,如果左子树不为空,则将左子树放入栈中,同样,如果右子树也不为空,则将右子树也放入栈中。
优化:需要判断当前节点是不是空
根据二叉搜索树的特点进行优化,分为以下几种情况:
- 如果当前节点的val大于high,则右子树的所有节点数值都大于high,则无需考虑右子树,只考虑左子树
- 如果当前节点的val小与low,则左子树的所有节点数值都小与low,则无需考虑左子树,只考虑右子树
- 当前节点满足条件,则左右子树的节点数值都需要考虑。
/**
* 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) {
stack<TreeNode*> s;
s.push(root);
int sum=0;
while(s.size()){
TreeNode* tmp=s.top();
s.pop();
if(tmp->val>=low &&tmp->val<=high){
sum+=tmp->val;
}
if(tmp->left !=NULL){
s.push(tmp->left);
}
if(tmp->right!=NULL){
s.push(tmp->right);
}
}
return sum;
}
};
优化版本:
/**
* 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) {
stack<TreeNode*> s;
s.push(root);
int sum=0;
while(s.size()){
TreeNode* tmp=s.top();
s.pop();
if(tmp==NULL)
{
continue;
}
if(tmp->val>=low &&tmp->val<=high){
sum+=tmp->val;
s.push(tmp->left);
s.push(tmp->right);
}
else if(tmp->val>high){
s.push(tmp->left);
}
else if(tmp->val<low){
s.push(tmp->right);
}
}
return sum;
}
};