938. 二叉搜索树的范围和

110 篇文章 0 订阅

在这里插入图片描述
在这里插入图片描述
利用bst的特性做,如果当前结点符合,就让sum加上当前的,并递归左右。如果当前小于low,就去右边就行了,否则就去左边。最后返回sum。
一开始考虑中序遍历,很明显这样很快,O(logn),中序就是O(n)了

class Solution {
public:
    void dfs(TreeNode* root, int low ,int high){
        if(root == nullptr) return;
        //根据low和high和val递归左边or右边
        if(root->val >= low && root->val <= high){
            sum += root->val;
            dfs(root->left,low,high);
            dfs(root->right,low,high);
        }
        else if(root->val < low){
            dfs(root->right,low,high);
        }
        else{
            dfs(root->left,low,high);
        }
    }
    int rangeSumBST(TreeNode* root, int low, int high) {
        //bst,碰到大于high的就停止
        dfs(root,low,high);
        return sum;
    }
private:
    int sum = 0;
};

碰到大于high就返回,但是没搞懂,为什么不能在上面就判断?后面搞懂了,因为比如一开始根结点是100,左节点是10,那么你在最开始就退出了,当然错了!!要在根操作那里进行判断

class Solution {
public:
    void dfs(TreeNode* root, int low ,int high){
        if(root == nullptr) return;
        //当前值超过了就直接return
        dfs(root->left,low,high);
        if(root->val > high) return;
        if(root->val >= low) sum += root->val;
        dfs(root->right,low,high);
    }
    int rangeSumBST(TreeNode* root, int low, int high) {
        //bst,碰到大于high的就停止
        dfs(root,low,high);
        return sum;
    }
private:
    int sum = 0;
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值