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

力扣.270. 最接近的二叉搜索树值(中序遍历思想)

文章目录

  • 题目描述
  • 思路
  • 复杂度
  • Code

题目描述

在这里插入图片描述在这里插入图片描述

思路

遍历思想(利用二叉树的中序遍历)

本题的难点在于可能存在多个答案,并且要返回最小的那一个,为了解决这个问题,我门则要利用上二叉搜索树中序遍历为有序序列的特性,具体到代码中(结合代码看):
1.我们用变量res记录最终的结果,同时在中序遍历位置处利用Math.abs(root.val - target) < Math.abs(res - target)边遍历边更新res的值(注意此处是小于号
2.根据 target 和 root.val 的相对大小决定去左右子树搜索:如果 target 比 root 大,那么 root 的左子树差值肯定更大,直接遍历右子树;如果 target 比 root 小,那么 root 的右子树差值肯定更大,直接遍历左子树
3.同时要注意深刻体会
二叉树的中序遍历
(即是在二叉树中遍历完当前根节点的左子树后再准备遍历右子树的时刻)

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为二叉树的节点个数

空间复杂度:

O ( h ) O(h) O(h);其中 h h h为二叉树的高度

Code

class Solution {int res = Integer.MAX_VALUE;public int closestValue(TreeNode root, double target) {traverse(root, target);return res;}// Write the if judgment logic in the middle order// so that it can be executed from small to large,// ensuring that the final result is the smallest valueprivate void traverse(TreeNode root, double target) {if (root == null) {return;}// Depending on the relative size of target and root.val,// search the left and right subtreesif (root.val < target) {// Mid-order position if (Math.abs(root.val - target) < Math.abs(res - target)) {res = root.val;}// If target is larger than root,// then root's left subtree difference must be larger,// and the right subtree is traversed directlytraverse(root.right, target);} else {// If target is smaller than root,// then root's right subtree difference must be larger,// and the left subtree is traversed directlytraverse(root.left, target);// Mid-order position if (Math.abs(root.val - target) < Math.abs(res - target)) {res = root.val;}}}
}
http://www.lryc.cn/news/532569.html

相关文章:

  • Yageo国巨的RC系列0402封装1%电阻库来了
  • wait/notify/join/设计模式
  • Windows Docker笔记-Docker拉取镜像
  • 七大排序思想
  • intra-mart实现简易登录页面笔记
  • SpringBoot整合RocketMQ
  • 深入理解 YUV Planar 和色度二次采样 —— 视频处理的核心技术
  • 项目顺利交付,几个关键阶段
  • 第七天 开始学习ArkTS基础,理解声明式UI编程思想
  • windows C++ Fiber (协程)
  • 游戏引擎学习第89天
  • 2025新鲜出炉--前端面试题(一)
  • 教程 | i.MX RT1180 ECAT_digital_io DEMO 搭建(一)
  • Pyecharts系列课程04——折线图/面积图(Line)
  • 变压器-000000
  • 凝思60重置密码
  • linux——网络计算机{序列化及反序列化(JSON)(ifdef的用法)}
  • 【教程】docker升级镜像
  • 迅为RK3568开发板篇OpenHarmony实操HDF驱动控制LED-编写应用APP
  • python代码
  • React 打印插件 -- react-to-print
  • 探索C语言简易计算器程序的实现与优化
  • 深入了解 MySQL:从基础到高级特性
  • OSPF基础(1):工作过程、状态机、更新
  • 工业相机如何获得更好的图像色彩
  • 使用requestAnimationFrame减少浏览器重绘
  • Mac 终端命令大全
  • 如何使用deepseek开发一个翻译API
  • vue如何解决跨域
  • 红包雨项目前端部分