LeetCode算法题-Trim a Binary Search Tree(Java实现)

matlab 用m_map画地形水深图 clear,clc %投影 m_proj('albers equal-area','lat',[5 43],'long',[105 125],'rect','on'); %加载水深文件 [CS,CH]=m_etopo2('contourf',[-7000:500:3000],'edgecolor','none'); %绘制高分辨率陆地和海岸线 m_gshhs_h('patch',[0.1 0.9 ... 阅读详情

这是悦乐书的第284次更新,第301篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第152题(顺位题号是669)。给定二叉搜索树以及L和R的最低和最高边界,修剪树以使其所有元素位于[L,R](R> = L)。可能需要更改树的根,因此结果应返回修剪后的二叉搜索树的新根。例如:

输入:L = 1 R = 2

    1
   / \
  0   2

输出:

     1
      \
       2

输入:L = 1 R = 3

    3
   / \
  0   4
   \
    2
   /
  1

输出:

      3
     / 
   2   
  /
 1

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

使用递归的方式。因为是二叉搜索树,并且返回的新二叉树的根节点值是未定的,需要先确定根节点在哪,确定完根节点后,再去确定它的左子树和右子树。如果当前节点值比右边界要大,那么新节点只可能在左子树那边;如果当前节点值比左边界还要小,那么新节点只能在右子树那边。剩下就是正常情况,新左节点还是在左边,新右节点还是在右边。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode trimBST(TreeNode root, int L, int R) {
        if (root == null) {
            return null;
        }
        if (root.val > R) {
            return trimBST(root.left, L, R);    
        }
        if (root.val < L) {
            return trimBST(root.right, L, R);
        }
        root.left = trimBST(root.left, L, R);
        root.right = trimBST(root.right, L, R);
        return root;
    }
}

03 第二种解法

使用迭代的方式。首先,还是需要确定根节点在哪里,使用一个循环来判断,如果当前节点值大于右边界,就往左子树里面找,如果小于左边界,就往右子树里面找。接着,从确定好的根节点开始,处理它的左子树,还是还是用循环,如果当前节点不为空,并且它的左节点本身也不为空,它的左节点值小于左边界,那么就跟换它的左节点,将当前节点的左节点重新指向到当前节点左节点的右子节点。同理,对于右子树的处理也是一样的逻辑,只是将判断换成了大于右边界值。最后返回新的二叉树。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode trimBST(TreeNode root, int L, int R) {
        if (root == null) {
            return null;
        }
        // 先确定根节点的位置
        while (root.val > R || root.val < L) {
            if (root == null) {
                return null;
            }
            if (root.val > R) {
                root = root.left;
            }
            if (root.val < L) {
                root = root.right;
            }
        }
        // 处理左子树
        TreeNode temp = root;
        while (temp != null) {
            // 如果当前节点的左节点不为空且节点值小于左边界
            while (temp.left != null && temp.left.val < L) {
                // 就将当前节点的左节点指向当前节点左节点的右子节点
                temp.left = temp.left.right;
            }
            temp = temp.left;
        }
        // 处理右子树
        temp = root;
        while (temp != null) {
            // 如果当前节点的右节点不为空且节点值大于右边界
            while (temp.right != null && temp.right.val > R) {
                // 就将当前节点的右节点指向当前节点右节点的左子节点
                temp.right = temp.right.left;
            }
            temp = temp.right;
        }
        return root;
    }
}

04 小结

算法专题目前已日更超过四个月,算法题文章152+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

什么是 Agent 的 Context Window?为什么它是 Agent 工程中最核心的约束之一? 阅读详情

相关推荐

【LDLTS解析】从重叠峰到精准参数:拉普拉斯深能级瞬态光谱如何重塑半导体缺陷分析

本文深入解析了拉普拉斯深能级瞬态光谱(LDLTS)技术如何革新半导体缺陷分析。针对传统DLTS难以分辨重叠峰的痛点,LDLTS通过拉普拉斯逆变换对高精度电容瞬态曲线进行数学解卷积,成功分离发射率相近的缺陷信号,实现从模糊宽峰到精准独立峰的转变。该技术不仅大幅提升了缺陷激活能和捕获截面等关键参数的提取精度,更推动分析范式从经验拟合转向第一性原理,为先进半导体工艺开发与良率提升提供了强大的精准诊断工具。

weixin_29224309的博客 275

LeetCode 669. Trim a Binary Search Tree

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result

菜园子 860

基于ROS2系统开发机器人

以上是基于ROS 2开发机器人的基本流程和一个简单的发布者-订阅者示例。通过这个流程,你可以逐步扩展和优化你的机器人系统,实现更复杂的功能。

xuweilin的博客 1496

C++实现擦除首尾空格的函数trim()实现

直接贴代码: void strspc(string &s){ int l = 0; int r = s.length()-1; //用于判断l和r是否扫到除空格以外字符。 int f1 = 0,f2 = 0; //用l<=r是为了让最后产生一个错位l=r+1,这样可以使得当处于全为空格时不会漏掉。 while (l<=r) { if(l<=r&&s[l]==' '){ l++; } else .

CppYyds的博客 1022

Zynq-PS-SDK(12) 之 VDMA+VTC+AXI4S-VideoOut 视频通路硬件搭建

前面分别叙述了《Zynq-PS-SDK(9) 之 VDMA》、《Zynq-PS-SDK(10) 之 VTC》以及《Zynq-PS-SDK(11) 之 AXI4-Stream To Video Out》;搭建一个简单的视频通路(Framebuffer -> HDMI)就要用到这些个模块,总体的设计框图如下所示: 视频数据的 Framebuffer 在 DDR 中,通过 Processing System 写入进去; 数据通过高带宽的 AXI4 接口(这里用到了 HP AXI,即 64bits 带

StephenZhou 5593

打造会自主学习的 AI 助手:OpenClaw 记忆系统完全指南

这不是科幻,这是我正在使用的系统。我的 AI 助手「小琳」已经运行了一段时间,积累了大量的知识和经验,而且还在不断学习成长。心跳(Heartbeat)是 OpenClaw 的定时轮询机制,可以让 AI 主动做一些事情。你有没有遇到过这样的困扰:每次和 AI 对话,它都像失忆了一样,之前聊过的内容完全不记得?设置定时任务:每天早上 8 点,查询天气和热点新闻,通过钉钉推送给我。让你的 AI 助手拥有持久记忆,能够自主学习、总结经验、不断成长。这不仅仅是一个「能记住事情的 AI」,而是一个。

Honmaple的博客 1634

python--leetcode669. Trim a Binary Search Tree

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the r

wenqiwenqi123的博客 1345

R数据分析:潜在剖面分析LPA的做法与解释

Latent Profile Analysis (LPA) tries to identify clusters of individuals (i.e., latent profiles) based on responses to a series of continuous variables (i.e., indicators). LPA assumes that there are unobserved latent profiles that generate patterns of resp.

Codewar的博客 1万+

【LeetCode】669.Trim a Binary Search Tree解题报告

【LeetCode】669.Trim a Binary Search Tree解题报告tags: Tree题目地址:https://leetcode.com/problems/trim-a-binary-search-tree/description/ 题目描述:   Given a binary search tree and the lowest and highest boundarie

郝春雨的博客 251

RK3588开发笔记-Buildroot编译host-nodejs报错解决ModuleNotFoundError: No module named ‘_bz2‘

在RK3588的开发过程中,使用Buildroot进行系统的构建和编译是一个常见的选择。然而,在编译host-nodejs的过程中,有时会遇到报错信息提示。这个错误通常是由于Python环境中缺少相应的模块导致的。以下将记录我解决这个问题的过程。。在RK3588的开发过程中,使用Buildroot编译host-nodejs时遇到的错误,通常是由于缺少相应的Python模块导致的。通过配置buildroot pythong bzip2开发库并重新编译,可以解决这个问题。

flypig has a dream! 901

雷达方程从零开始的详细推导及实现

通过以上六步,我们从最基本的物理图像出发,完整地推导出了雷达方程。初学者可以按照这个逻辑,自己在纸上一步步重现整个过程。Python实现。

VectorShift的博客 338

LeetCode-669. Trim a Binary Search Tree [C++][Java]

Given therootof a binary search tree and the lowest and highest boundaries aslowandhigh, trim the tree so that all its elements lies in[low, high]. Trimming the tree shouldnotchange the relative structure of the elements

贫道绝缘子的博客 151

肖特基二极管的反向恢复过程

本博客简述肖特基二极管反向恢复过程。

记得诚 1万+

LeetCode-Trim a Binary Search Tree

LeetCode Java Trim a Binary Search Tree

坟头草一米七五 151

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

[LeetCode] 669. Trim a Binary Search Tree

题:https://leetcode.com/problems/trim-a-binary-search-tree/description/ 题目 Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L...

u013383813的博客 156

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Java描述 LeetCode,669. Trim a Binary Search Tree 修剪二叉搜索树

修剪二叉树,关键是删除一部分节点,或者左子树,或者右子树,再将重构之后的节点代替原来的节点连接起来就行。

人在江湖 934

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

leetcode 669 Trim a Binary Search Tree

Java class Solution { public TreeNode trimBST(TreeNode root, int L, int R) { if(root==null) return null; if(root.val<L) return trimBST(root.right,L,R); if(root.va

MRxjh的博客 234

LeetCode 669. 修剪二叉搜索树(Trim a Binary Search Tree)

669. 修剪二叉搜索树 669. Trim a Binary Search Tree 题目描述 LeetCode LeetCode669. Trim a Binary Search Tree简单 Java 实现 TreeNode Class public class TreeNode { int val; TreeNode left; TreeNode right; ...

weixin_30835649的博客 121

leetcode 669. Trim a Binary Search Tree 修剪二叉搜索树 (简单)

什么是二叉查找树? 二叉查找树(Binary Search Tree,BST)是一种特殊的二叉树:对于每个父节点,其左子树中所有节点的值小于等于父节点的值,其右子树中所有节点的值大于等于父节点的值。 利用二叉查找树的大小关系,我们可以很容易地利用递归进行树的处理。

ln_ydc的专栏 207

LeetCode Trim a Binary Search Tree

原题链接在这里:https://leetcode.com/problems/trim-a-binary-search-tree/description/ 题目: Given a binary search tree and the lowest and highest boundaries asLandR, trim the tree so that all its elements...

weixin_30706507的博客 79

leetcode(669):Trim a Binary Search Tree

题目:Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the res

赵小越的博客 236

669. Trim a Binary Search Tree

这个比较简单 https://leetcode.com/problems/trim-a-binary-search-tree/discuss/107000/Java-solution-6-liner 1 //Old 2 class Solution { 3 TreeNode dummy = new TreeNode(Integer.MAX...

diegouyi3472的博客 80

[leetcode] 669. Trim a Binary Search Tree @ python

原题 Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R &gt;= L). You might need to change the root of the tree, so the...

闲庭信步 314

(Java)leetcode-669 Trim a Binary Search Tree(修剪二叉搜索树)

递归!套娃!

不思量 215

[Leetcode] 669. Trim a Binary Search Tree 解题报告

题目: Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree,

魔豆(Magicbean)的博客 258
上一篇: LeetCode算法题-Non-decreasing Array(Java实现)
下一篇: LeetCode算法题-Second Minimum Node In a Binary Tree(Java实现)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值