[LC] 270. Closest Binary Search Tree Value
2024-10-08 20:00:07
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
- Given target value is a floating point.
- You are guaranteed to have only one unique value in the BST that is closest to the target.
Example:
Input: root = [4,2,5,1,3], target = 3.714286 4
/ \
2 5
/ \
1 3 Output: 4
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int closestValue(TreeNode root, double target) {
if (root == null) {
return -1;
}
int res = root.val;
while (root != null) {
if (Math.abs(root.val - target) < Math.abs(res - target)) {
res = root.val;
}
if (root.val > target) {
root = root.left;
} else {
root = root.right;
}
}
return res;
}
}
最新文章
- 安装zeppelin
- 思维题(转换) HDU 4370 0 or 1
- 写hive db的两种方法
- transactional replication 的immediate_sync属性
- 突破XSS字符数量限制执行任意JS代码
- c++中try catch的用法
- sql语句中like的使用
- poj1036-dp
- 【MongoDB】学习MongoDB推荐三本书
- 设计模式(一)&mdash;单例模式
- cisco模拟器之------交换机、路由器、vlan的综合实例
- Android隐藏软键盘
- 常用VI操作命令
- mysql 索引中的USING BTREE 的意义
- python 截取 取出一部分的字符串
- Nginx高级配置,同1台机器部署多个tomcat、配置多个域名,每个域名指向某一个tomcat下的项目,共用Nginx80端口访问;
- python入门之列表
- 使用markdown第一个博客
- css3中的BFC,IFC,GFC和FFC
- Java 5- Java 修饰符