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.

给一个非空二叉树和一个目标值,找到和目标值最接近的一个节点值。

利用二分搜索树的特点(左<根<右)来快速定位,由于根节点是中间值,在遍历时,如果目标值小于节点值,则找更小的值到左子树去找,反之去右子树找。

解法1:迭代

解法2:递归

Java:

public int closestValue(TreeNode root, double target) {
double min=Double.MAX_VALUE;
int result = root.val; while(root!=null){
if(target>root.val){ double diff = Math.abs(root.val-target);
if(diff<min){
min = Math.min(min, diff);
result = root.val;
}
root = root.right;
}else if(target<root.val){ double diff = Math.abs(root.val-target);
if(diff<min){
min = Math.min(min, diff);
result = root.val;
}
root = root.left;
}else{
return root.val;
}
} return result;
}  

Java:

public class Solution {
int goal;
double min = Double.MAX_VALUE; public int closestValue(TreeNode root, double target) {
helper(root, target);
return goal;
} public void helper(TreeNode root, double target){
if(root==null)
return; if(Math.abs(root.val - target) < min){
min = Math.abs(root.val-target);
goal = root.val;
} if(target < root.val){
helper(root.left, target);
}else{
helper(root.right, target);
}
}
} 

Java: 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) {
if (root == null) return 0;
int min = root.val;
while (root != null) {
min = (Math.abs(root.val - target) < Math.abs(min - target) ? root.val : min);
root = (root.val < target) ? root.right : root.left;
}
return min;
}
}

Java: Recursion

/**
* 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) {
TreeNode child = target < root.val ? root.left : root.right;
if (child == null) {
return root.val;
}
int childClosest = closestValue(child, target);
return Math.abs(root.val - target) < Math.abs(childClosest - target) ? root.val : childClosest;
}
}

Python: Iteration, Time: O(h), Space: O(1)

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def closestValue(self, root, target):
"""
:type root: TreeNode
:type target: float
:rtype: int
"""
gap = float("inf")
closest = float("inf")
while root:
if abs(root.val - target) < gap:
gap = abs(root.val - target)
closest = root
if target == root.val:
break
elif target < root.val:
root = root.left
else:
root = root.right
return closest.val

C++: Iteration

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int closestValue(TreeNode* root, double target) {
double gap = numeric_limits<double>::max();
int closest = numeric_limits<int>::max(); while (root) {
if (abs(static_cast<double>(root->val) - target) < gap) {
gap = abs(root->val - target);
closest = root->val;
}
if (target == root->val) {
break;
} else if (target < root->val) {
root = root->left;
} else {
root = root->right;
}
}
return closest;
}
}; 

C++: Iteration

class Solution {
public:
int closestValue(TreeNode* root, double target) {
int res = root->val;
while (root) {
if (abs(res - target) >= abs(root->val - target)) {
res = root->val;
}
root = target < root->val ? root->left : root->right;
}
return res;
}
};

C++: Recursion

class Solution {
public:
int closestValue(TreeNode* root, double target) {
int a = root->val;
TreeNode *t = target < a ? root->left : root->right;
if (!t) return a;
int b = closestValue(t, target);
return abs(a - target) < abs(b - target) ? a : b;
}
};

C++: Recursion

class Solution {
public:
int closestValue(TreeNode* root, double target) {
int res = root->val;
if (target < root->val && root->left) {
int l = closestValue(root->left, target);
if (abs(res - target) >= abs(l - target)) res = l;
} else if (target > root->val && root->right) {
int r = closestValue(root->right, target);
if (abs(res - target) >= abs(r - target)) res = r;
}
return res;
}
};  

类似题目:

  

All LeetCode Questions List 题目汇总

最新文章

  1. php function集合
  2. Sprint1(第四天11.17)
  3. 使用spring boot和thrift、zookeeper建立微服务
  4. jquery动态创建页面元素
  5. Java 实现奇数阶幻方的构造
  6. 【树莓PI】下载机
  7. cheerio返回数据格式
  8. stl之map容器的原理及应用
  9. Visual Studio 2015 &amp; C#6.0
  10. 关于PHP创建接口及调用接口的简短例子(本地)
  11. iOS视频流开发(1)—视频基本概念
  12. 论文笔记之:DualGAN: Unsupervised Dual Learning for Image-to-Image Translation
  13. hdu 3832 Earth Hour bfs
  14. openwrt手工配置pptpd
  15. Python小任务 - 如何编写指定时间执行的Python小程序
  16. redis.conf 配置
  17. 导出/打印项目数据报表需要设置IE浏览器
  18. mysql replace()用法
  19. lintcode-111-爬楼梯
  20. F12 chrome开发者工具

热门文章

  1. Codeforces E. Alyona and a tree(二分树上差分)
  2. waitpid()函数
  3. Spring框架的JDBC模板技术和事物
  4. BZOJ 1034: [ZJOI2008]泡泡堂BNB 贪心+排序
  5. vue echarts 给双饼图添加点击事件
  6. 【loj3059】【hnoi2019】序列
  7. mint-ui里面的MessageBox怎么去判断确认还是取消
  8. 给.sh文件添加执行权限linux
  9. 帝国CMS 7.5编辑器从WORD中粘贴过来无法保留格式和图片的解决办法
  10. hotspot编译