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 题目汇总

[LeetCode] 270. Closest Binary Search Tree Value 最近的二叉搜索树的值的更多相关文章

  1. [LeetCode] 272. Closest Binary Search Tree Value II 最近的二分搜索树的值之二

    Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...

  2. [LeetCode] Trim a Binary Search Tree 修剪一棵二叉搜索树

    Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that a ...

  3. [LeetCode] Closest Binary Search Tree Value II 最近的二分搜索树的值之二

    Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...

  4. Leetcode 270. Closest Binary Search Tree Value

    Given a non-empty binary search tree and a target value, find the value in the BST that is closest t ...

  5. [leetcode]270. Closest Binary Search Tree Value二叉搜索树中找target的最接近值

    Given a non-empty binary search tree and a target value, find the value in the BST that is closest t ...

  6. leetCode 95.Unique Binary Search Trees II (唯一二叉搜索树) 解题思路和方法

    Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For e ...

  7. 109 Convert Sorted List to Binary Search Tree 有序链表转换二叉搜索树

    给定一个单元链表,元素按升序排序,将其转换为高度平衡的BST.对于这个问题,一个高度平衡的二叉树是指:其中每个节点的两个子树的深度相差不会超过 1 的二叉树.示例:给定的排序链表: [-10, -3, ...

  8. Leetcode109. Convert Sorted List to Binary Search Tree有序链表转换二叉搜索树

    给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树. 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1. 示例: 给定的有序链表: [-10 ...

  9. [LeetCode] 272. Closest Binary Search Tree Value II 最近的二叉搜索树的值 II

    Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...

随机推荐

  1. 如何查看已购买的office密钥

    登陆这个网址https://account.microsoft.com/services/ 声明 :转载请注明来源sogeisetsu.cnblogs.com

  2. CodeForces - 95E: Lucky Country (多重背包)

    pro:给定N个点,M条边,现在你要给一些连通块加边,使得至少存在一个连通块的大小是由4和7组成的数字.问至少加边数量. sol: 看似一个很难的题目.  首先不要想太难了,还是应该想能不能用背包做. ...

  3. VMware共享本地文件

    最后可以在这里找到

  4. mybatis框架-SqlSession会话操作数据库的两种方式

    1.通过SqlSession实力来直接执行已经映射的sql语句 例如,查询整个用户表中的信息 在UserMapper.xml中编写sql语句 编写测试方法: 注意:这里使用的selectList方法: ...

  5. 微信小程序——音频播放器

    先来个效果图韵下味: 需求: 音频的播放,暂停,中间按钮状态的变化,播放时实时更新播放进度: 前进15s,后退15s: 进度条拖动. 一开始想着这3个功能应该挺简单的.不就是播放,暂停,前进,后退么~ ...

  6. HDU 2887 Watering Hole(MST + 倍增LCA)

    传送门 总算是做上一道LCA的应用题了... 题意:有$n$个牧场, $m$根管道分别连接编号为$u,v$的牧场花费$p_{i}$,在第$i$个牧场挖口井需要花费$w_{i}$,有$P$根管道直接连通 ...

  7. NOIP爆炸记

    NOIP爆炸游记 Day 0 Day 1 T1 T2 T3 Day 2 T1 T2 T3 最后 Day 0 复习模板 + 做真题 + 方 Day 1 早上吃了一片面包,就进了考场- T1 Exm??这 ...

  8. 【洛谷P4319】 变化的道路 线段树分治+LCT

    最近学了一下线段树分治,感觉还蛮好用... 如果正常动态维护最大生成树的话用 LCT 就行,但是这里还有时间这一维的限制. 所以,我们就把每条边放到以时间为轴的线段树的节点上,然后写一个可撤销 LCT ...

  9. Tomcat启动问题:严重[main] org.apache.catalina.core.AprLifecycleListener.init An incompatible version...

    今天观察tomcat启动日志,有一些以前没注意到的信息: 严重 [main] org.apache.catalina.core.AprLifecycleListener.init An incompa ...

  10. 14-ESP8266 SDK开发基础入门篇--上位机串口控制 Wi-Fi输出PWM的占空比,调节LED亮度,8266程序编写

    https://www.cnblogs.com/yangfengwu/p/11102026.html 首先规定下协议  ,CRC16就不加了哈,最后我会附上CRC16的计算程序,大家有兴趣自己加上 上 ...