《沈娜娜》高清在线观看:一段穿越时光的情感羁绊

核心内容摘要

YSL水蜜桃86:解锁夏日水光肌的秘密
男生女生愁愁

暗黑蘑菇17c:开启未知边缘的神秘邀约

给你二叉搜索树的根节点root和一个目标值target请在该二叉搜索树中找到最接近目标值target的数值。

如果有多个答案返回最小的那个。

示例 1输入root [4,2,5,1,3], target

714286输出4示例 2输入root [1], target

428571输出1提示树中节点的数目在范围[1, 104]内0 Node.val

target 109直接上代码/** * 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我懒得用

3Dmax9视频在线-3Dmax9视频在线应用

百度百家号客服电话人工服务

123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123