摇摆的激情:当脱色遇上剧烈运动与扑克

核心内容摘要

守护正义的清流:白峰美羽的检察官之路
探索“欧美精产国品一二三区别”:一部关于品质与品味的鉴赏之旅

1980:女兵、军舰与满天星辰——一段热血年代的青春赞歌

给你二叉搜索树的根节点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我懒得用

蔴花豆传禖永久免费-蔴花豆传禖永久免费应用

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

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