Leetcode 938.二叉搜索树的范围和

题目描述:

给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
https://leetcode-cn.com/problems/range-sum-of-bst/

解题思路:

二叉搜索树是按照中序遍历,root = [10,5,15,3,7,null,18], low = 7, high = 15,中序遍历结果是3,5,7,10,15,18,从7到15,即为7+10+15=32,所以关键是得到中序遍历的结果,我通过深搜,将遍历结果放在result里,再对result进行遍历,将区间内的数加起来,这样做时间复杂度和空间复杂度都很高,555555

c++代码:

class Solution {
public:
    int rangeSumBST(TreeNode* root, int low, int high) {
            vector<int> result;
            int re=0;
            dfs(root,result);
            for(int i=0,j=result.size()-1;i<=j;){
                if(result[i]!=low) i++;
                if(result[j]!=high) j--;
                if(result[i]==low&&result[j]==high){
                    for(int t=i;t<=j;t++){
                        re+=result[t];
                    }
                    break;
                }
            }
            return re;
    }
    void dfs(TreeNode* root,vector<int>& result){
        if(root==nullptr) return;
        dfs(root->left,result);
        result.push_back(root->val);
        dfs(root->right,result);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值