Leetcode会员尊享100题:270.最接近的二叉树值

给你二叉搜索树的根节点 root 和一个目标值 target ,请在该二叉搜索树中找到最接近目标值 target 的数值。如果有多个答案,返回最小的那个。

示例 1:

复制代码
输入:root = [4,2,5,1,3], target = 3.714286
输出:4

示例 2:

复制代码
输入:root = [1], target = 4.428571
输出:1

提示:

  • 树中节点的数目在范围 [1, 104]
  • 0 <= Node.val <= 109
  • -109 <= target <= 109

直接上代码:

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int closestValue(TreeNode root, double target) {
        Info info = getInfo(root, target);
        return info.value;
    }

    public Info getInfo(TreeNode root, double target) {
        if(root == null) {
            return new Info(Integer.MAX_VALUE, Integer.MAX_VALUE);
        }
        if(root.left == null && root.right == null) {
            return new Info(root.val, Math.abs(root.val - target));
        }
        /**拿到左右子树的信息 */
        Info leftInfo = getInfo(root.left, target);
        Info rightInfo = getInfo(root.right, target);
        /**当前的最小差是左右树的最小差以及跟节点和target的差的最小值 */
        double distance = Math.min(Math.abs(root.val - target), Math.min(leftInfo.distance, rightInfo.distance));
        int value = distance == leftInfo.distance? leftInfo.value : distance == rightInfo.distance? rightInfo.value : root.val;
        /**有可能有重复的值,需要判断取最小那个 */
        if(distance == leftInfo.distance) {
            value = Math.min(value, leftInfo.value);
        }
        if(distance == rightInfo.distance) {
            value = Math.min(value, rightInfo.value);
        }
        if(distance == Math.abs(root.val - target)) {
            value = Math.min(value, root.val);
        }
        /**返回当前树的信息 */
        return new Info(value, distance);
    }
}

class Info {
    int value;
    double distance;
    public Info(int value, double distance) {
        this.value = value;
        this.distance = distance;
    }
}

看不懂的请私信或者留言,二叉树的所有问题,我倾向于使用二叉树的递归套路,这个题其实可以用DFS,我懒得用

相关推荐
踩坑记录1 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode
旖-旎1 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
谭欣辰1 小时前
C++快速幂完整实战讲解
算法·决策树·机器学习
Mr_pyx1 小时前
【LeetHOT100】随机链表的复制——Java多解法详解
算法·深度优先
AIFarmer1 小时前
【无标题】
开发语言·c++·算法
AGV算法笔记2 小时前
CVPR 2025 最新感知算法解读:GaussianLSS 如何用 Gaussian Splatting 重构 BEV 表示?
算法·重构·自动驾驶·3d视觉·感知算法·多视角视觉
勤劳的进取家2 小时前
数据链路层基础
网络·学习·算法
Advancer-3 小时前
第二次蓝桥杯总结(上)
java·算法·职场和发展·蓝桥杯
ん贤3 小时前
加密算法(对称、非对称、哈希、签名...)
算法·哈希算法
superior tigre4 小时前
78 子集
算法·leetcode·深度优先·回溯