当前位置: 首页 > article >正文

代码随想录算法训练营Day18

669. 修剪二叉搜索树

力扣题目链接:. - 力扣(LeetCode)

class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if(root==null){
            return null;
        }
        if(root.val<low){
            return trimBST(root.right,low,high);
        }
        if(root.val>high){
            return trimBST(root.left,low,high);
        }
        root.left=trimBST(root.left,low,high);
        root.right=trimBST(root.right,low,high);
        return root;
    }
}

108.将有序数组转换为二叉搜索树

力扣题目链接:. - 力扣(LeetCode)

循环不变量普遍用于二分查找和递归分割数组

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        int length=nums.length;
       return transform(nums,0,length);
    }
    public TreeNode transform(int[] nums,int left,int right){
        if(right-left<1){
            return null;
        }
        if(right-left==1){
            return new TreeNode(nums[left]);
        }
        int mid=left+(right-left)/2;
        TreeNode root=new TreeNode(nums[mid]);
        root.left=transform(nums,left,mid);
        root.right=transform(nums,mid+1,right);
        return root;
    }
}

538.把二叉搜索树转换为累加树

力扣题目链接:. - 力扣(LeetCode)

逆中序遍历

class Solution {
    int sum;
    public TreeNode convertBST(TreeNode root) {
        sum=0;
        count(root);
        return root;
    }
    public void count(TreeNode root){
        if(root==null){
            return;
        }
        count(root.right);
        sum+=root.val;
        root.val=sum;
        count(root.left);
    }
}


http://www.kler.cn/news/342182.html

相关文章:

  • Internet Download Manager6.42免费版下载神器新体验
  • codetop标签动态规划大全C++讲解(二)!!动态规划刷穿地心!!学吐了家人们o(╥﹏╥)o
  • 在线教育新篇章:SpringBoot系统开发策略
  • Vscode+Pycharm+Vue.js+WEUI+django火锅(三)理解Vue
  • WPF|依赖属性SetCurrentValue方法不会使绑定失效, SetValue方法会使绑定失效?是真的吗?
  • 2024.10月7~10日 进一步完善《电信资费管理系统》
  • 自动驾驶系列—从IMU到惯性定位算法:自动驾驶精准定位的幕后科技
  • 制造业人工智能的场景应用落地现状、难点和建议
  • 力扣10.9
  • 【数据结构】6道经典链表面试题
  • Ubuntu 更换内核版本
  • 单目三d重建学习笔记2024
  • 从开发效率到查询性能:JPA 和 MyBatis 在企业系统中的完美结合
  • Git 工作区、暂存区和仓库
  • 跟《经济学人》学英文:2024年10月05日这期 Workouts for the face are a growing business
  • python画图|步进图基本教程
  • 【C语言系统编程】【第三部分:网络编程】3.3 实践与案例分析
  • 解读 AI 获客关键要素,开启营销新未来
  • 架构设计(14)分布式系统的CAP,BASE与ACID
  • JavaScript 网页设计案例详解