力扣.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;
            }
        }
    }
}
相关推荐
叫我阿柒啊12 分钟前
从Java全栈到前端框架:一位程序员的实战之路
java·spring boot·微服务·消息队列·vue3·前端开发·后端开发
mqiqe31 分钟前
架构-亿级流量性能调优实践
java·架构
j_xxx404_44 分钟前
数据结构:栈和队列力扣算法题
c语言·数据结构·算法·leetcode·链表
南莺莺1 小时前
假设一个算术表达式中包含圆括号、方括号和花括号3种类型的括号,编写一个算法来判别,表达式中的括号是否配对,以字符“\0“作为算术表达式的结束符
c语言·数据结构·算法·
Lris-KK1 小时前
【Leetcode】高频SQL基础题--180.连续出现的数字
sql·leetcode
THMAIL1 小时前
深度学习从入门到精通 - 神经网络核心原理:从生物神经元到数学模型蜕变
人工智能·python·深度学习·神经网络·算法·机器学习·逻辑回归
珍珠是蚌的眼泪1 小时前
LeetCode_位运算
leetcode·位运算·异或·韩明距离·数字的补数
野犬寒鸦1 小时前
力扣hot100:旋转图像(48)(详细图解以及核心思路剖析)
java·数据结构·后端·算法·leetcode
墨染点香1 小时前
LeetCode 刷题【61. 旋转链表】
算法·leetcode·职场和发展
七夜zippoe1 小时前
AI+Java 守护你的钱袋子!金融领域的智能风控与极速交易
java·人工智能·金融