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;
}
}

最新文章

  1. 安装zeppelin
  2. 思维题(转换) HDU 4370 0 or 1
  3. 写hive db的两种方法
  4. transactional replication 的immediate_sync属性
  5. 突破XSS字符数量限制执行任意JS代码
  6. c++中try catch的用法
  7. sql语句中like的使用
  8. poj1036-dp
  9. 【MongoDB】学习MongoDB推荐三本书
  10. 设计模式(一)&mdash;单例模式
  11. cisco模拟器之------交换机、路由器、vlan的综合实例
  12. Android隐藏软键盘
  13. 常用VI操作命令
  14. mysql 索引中的USING BTREE 的意义
  15. python 截取 取出一部分的字符串
  16. Nginx高级配置,同1台机器部署多个tomcat、配置多个域名,每个域名指向某一个tomcat下的项目,共用Nginx80端口访问;
  17. python入门之列表
  18. 使用markdown第一个博客
  19. css3中的BFC,IFC,GFC和FFC
  20. Java 5- Java 修饰符

热门文章

  1. JavaSE--java是值传递还是引用传递
  2. trove module使用说明
  3. JZOJPJ-C 8/21题解
  4. c#中的Task异步编程
  5. elasticsearch + springboot 整合
  6. .net学习——第一个程序
  7. HttpClient4.x 上传文件
  8. 【论文笔记系列】AutoML:A Survey of State-of-the-art (下)
  9. 系统学习python第四天学习笔记
  10. C语言程序设计|05