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

文章目录

题目描述

思路

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

本题的难点在于可能存在多个答案,并且要返回最小的那一个 ,为了解决这个问题,我门则要利用上二叉搜索树中序遍历为有序序列 的特性,具体到代码中(结合代码看):

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

java 复制代码
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 value
    private 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 subtrees
        if (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 directly
            traverse(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 directly
            traverse(root.left, target);
            
            // Mid-order position 
            if (Math.abs(root.val - target) < Math.abs(res - target)) {
                res = root.val;
            }
        }
    }
}
相关推荐
Gu_yyqx1 分钟前
IDEA中debug的使用
java·ide·intellij-idea
zore_c2 分钟前
【数据结构】队列——超详解!!!(包含队列的实现)
c语言·网络·数据结构·c++·笔记·算法·链表
小杰帅气4 分钟前
智能指针喵喵喵
开发语言·c++·算法
老华带你飞4 分钟前
个人网盘管理|基于springboot + vue个人网盘管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
宸津-代码粉碎机5 分钟前
告别繁琐SQL!MyBatis - Flex让数据库操作“飞”起来
java·服务器·tomcat
艾莉丝努力练剑12 分钟前
【Linux进程(四)】深入理解 Linux O(1) 调度器:双队列轮转与进程优先级机制——如何避免进程饥饿,实现公平且高效的进程调度
java·大数据·linux·运维·服务器·人工智能·安全
智驱力人工智能13 分钟前
守护生命的水上之眼 无人机人员落水检测系统的技术攻坚与应用实践 无人机溺水识别 山区水库无人机落水检测系统 水域安全无人机部署指南
大数据·人工智能·算法·安全·无人机·边缘计算
hweiyu0015 分钟前
排序算法选型决策树
算法·排序算法
郑州光合科技余经理1 小时前
PHP构建:支撑欧美澳市场的同城生活服务平台开发
java·开发语言·数据库·uni-app·php·排序算法·生活
蓝色汪洋2 小时前
xtu oj矩阵
算法