270. Closest Binary Search Tree Value
2016-03-31 12:35
239 查看
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.
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.
Solution 1. Iteration /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int closestValue(TreeNode root, double target) { double diff = Double.MAX_VALUE; int val = root.val; while (root != null) { if (diff > Math.abs(root.val - target)) { val = root.val; diff = Math.abs(root.val - target); } if (root.val > target) { root = root.left; } else { root = root.right; } } return val; } } Solution 2. Recursion public class Solution { public int closestValue(TreeNode root, double target) { int a = root.val; TreeNode kid = target < a ? root.left : root.right; if (kid == null) return a; int b = closestValue(kid, target); return Math.abs(a - target) < Math.abs(b - target) ? a : b; } }
相关文章推荐
- HDU 1159 Common Subsequence (dp)
- FreeMarker boolean Issue
- 302. Smallest Rectangle Enclosing Black Pixels My Submissions QuestionEditorial Solution
- Issues about gradle version and Android Plugin Version
- Mybatis报TypeException:JDBC requires that the JdbcType must be specified for all nullable parameters.
- DruidDataSource配置
- 定义一个Map对象,遍历并打印出各元素的key和value
- OnClick与android:focusableInTouchMode="true"
- Microsoft Build 2016 Day 1 记录
- ios学习--layer的应用(设置UIView子类边框属性&字体阴影属性)
- Vue.js 综合
- UITableView的使用
- HDU 3998 Sequence(LIS+最大流-Dinic)
- iOS:Cocoa编码规范 -[译]Coding Guidelines for Cocoa
- 《iOS Human Interface Guidelines》——Slider
- requirejs 一个拆分js项目的类库
- AndroidUI设计思想:程序易用性
- php采集(phpOuery用法)
- 微软 Build 2016年开发者大会发布多项功能升级
- 百度编辑器ueditor 多图上传 文件格式不允许 后台配置项返回出错 解决方法