270:最接近的二叉搜索树值

This commit is contained in:
轩辕龙儿 2022-04-11 13:59:58 +08:00
parent c34a34591a
commit 541b2ee2af
2 changed files with 102 additions and 0 deletions

View File

@ -0,0 +1,80 @@
//给定一个不为空的二叉搜索树和一个目标值 target请在该二叉搜索树中找到最接近目标值 target 的数值
//
// 注意
//
//
// 给定的目标值 target 是一个浮点数
// 题目保证在该二叉搜索树中只会存在一个最接近目标值的数
//
//
// 示例
//
// 输入: root = [4,2,5,1,3]目标值 target = 3.714286
//
// 4
// / \
// 2 5
// / \
//1 3
//
//输出: 4
//
// Related Topics 深度优先搜索 二叉搜索树 二分查找 二叉树 👍 112 👎 0
package leetcode.editor.cn;
import com.code.leet.entiy.TreeNode;
//270:最接近的二叉搜索树值
public class ClosestBinarySearchTreeValue {
public static void main(String[] args) {
Solution solution = new ClosestBinarySearchTreeValue().new Solution();
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
/**
* 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) {
double left = target;
double right = target;
float diff = 1e-6f;
while (root != null) {
if (Math.abs(root.val - target) < diff) {
return root.val;
}
if (root.val > target) {
right = root.val;
root = root.left;
} else {
left = root.val;
root = root.right;
}
}
if (Math.abs(left - target) < diff) {
return (int) right;
} else if (Math.abs(right - target) < diff) {
return (int) left;
} else {
return target - left > right - target ? (int) right : (int) left;
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,22 @@
<p>给定一个不为空的二叉搜索树和一个目标值 target请在该二叉搜索树中找到最接近目标值 target 的数值。</p>
<p><strong>注意:</strong></p>
<ul>
<li>给定的目标值 target 是一个浮点数</li>
<li>题目保证在该二叉搜索树中只会存在一个最接近目标值的数</li>
</ul>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong> root = [4,2,5,1,3],目标值 target = 3.714286
4
/ \
2 5
/ \
1 3
<strong>输出:</strong> 4
</pre>
<div><div>Related Topics</div><div><li></li><li>深度优先搜索</li><li>二叉搜索树</li><li>二分查找</li><li>二叉树</li></div></div><br><div><li>👍 112</li><li>👎 0</li></div>