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

这道题让我们找一个二分搜索数的跟给定值最接近的一个节点值,由于是二分搜索树,所以博主最先想到用中序遍历来做,一个一个的比较,维护一个最小值,不停的更新,实际上这种方法并没有提高效率,用其他的遍历方法也可以,参见代码如下:

解法一:

class Solution {
public:
int closestValue(TreeNode* root, double target) {
double d = numeric_limits<double>::max();
int res = ;
stack<TreeNode*> s;
TreeNode *p = root;
while (p || !s.empty()) {
while (p) {
s.push(p);
p = p->left;
}
p = s.top(); s.pop();
if (d >= abs(target - p->val)) {
d = abs(target - p->val);
res = p->val;
}
p = p->right;
}
return res;
}
};

实际我们可以利用二分搜索树的特点 (左<根<右) 来快速定位,由于根节点是中间值,在往下遍历时,根据目标值和根节点的值大小关系来比较,如果目标值小于节点值,则应该找更小的值,于是到左子树去找,反之去右子树找,参见代码如下:

解法二:

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

以上两种方法都是迭代的方法,下面来看递归的写法,下面这种递归的写法和上面迭代的方法思路相同,都是根据二分搜索树的性质来优化查找,但是递归的写法用的是回溯法,先遍历到叶节点,然后一层一层的往回走,把最小值一层一层的运回来,参见代码如下:

解法三:

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

再来看另一种递归的写法,思路和上面的都相同,写法上略有不同,用if来分情况,参见代码如下:

解法三:

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

最后来看一种分治法的写法,这种方法相当于解法一的递归写法,并没有利用到二分搜索树的性质来优化搜索,参见代码如下:

解法四:

class Solution {
public:
int closestValue(TreeNode* root, double target) {
double diff = numeric_limits<double>::max();
int res = ;
helper(root, target, diff, res);
return res;
}
void helper(TreeNode *root, double target, double &diff, int &res) {
if (!root) return;
if (diff >= abs(root->val - target)) {
diff = abs(root->val - target);
res = root->val;
}
helper(root->left, target, diff, res);
helper(root->right, target, diff, res);
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/270

类似题目:

Count Complete Tree Nodes

Closest Binary Search Tree Value II

Search in a Binary Search Tree

参考资料:

https://leetcode.com/problems/closest-binary-search-tree-value/

https://leetcode.com/problems/closest-binary-search-tree-value/discuss/70331/Clean-and-concise-java-solution

https://leetcode.com/problems/closest-binary-search-tree-value/discuss/70322/Super-clean-recursive-Java-solution

https://leetcode.com/problems/closest-binary-search-tree-value/discuss/70327/4-7-lines-recursiveiterative-RubyC%2B%2BJavaPython

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

  1. [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 ...

  2. LeetCode Closest Binary Search Tree Value II

    原题链接在这里:https://leetcode.com/problems/closest-binary-search-tree-value-ii/ 题目: Given a non-empty bin ...

  3. LeetCode Closest Binary Search Tree Value

    原题链接在这里:https://leetcode.com/problems/closest-binary-search-tree-value/ Given a non-empty binary sea ...

  4. ✡ leetcode 173. Binary Search Tree Iterator 设计迭代器(搜索树)--------- java

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

  5. Closest Binary Search Tree Value I & II

    Closest Binary Search Tree Value Given a non-empty binary search tree and a target value, find the v ...

  6. [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 ...

  7. [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 ...

  8. 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 close ...

  9. LeetCode: Validata Binary Search Tree

    LeetCode: Validata Binary Search Tree Given a binary tree, determine if it is a valid binary search ...

随机推荐

  1. Ajax接收不到PHP return后的结果的原因

    PHP在处理ajax返回值的时候,如果使用return如 return $result会失败,echo $result却没问题. 解释原因如下: 1.ajax请求从服务器端读取返回值,而且这些返回值必 ...

  2. javaWeb应用打包

    在Java中,使用"jar"命令来对将JavaWeb应用打包成一个War包,jar命令的用法如下:

  3. 介绍,介绍我的底层支持库 Net.Sz.CFramework

    Net.Sz.CFramework  是我自己的底层库,是经过验证的底层库. 包含: socket tcp协议,socket http协议线程池,线程模型,任务模型,定时器模型,日志模块脚本模块一些辅 ...

  4. h1、h2、h3标签及strong标签对页面seo的影响

    今天和大家来聊下h1,h2,h3,strong几个标签,在网页中的使用对页面seo的影响,也阐述了个人的一些想法. 首先简要讲下H标签及strong标签的含义:<h1>.<h2> ...

  5. C#中HttpClient使用注意:预热与长连接

    最近在测试一个第三方API,准备集成在我们的网站应用中.API的调用使用的是.NET中的HttpClient,由于这个API会在关键业务中用到,对调用API的整体响应速度有严格要求,所以对HttpCl ...

  6. 细谈Slick(6)- Projection:ProvenShape,强类型的Query结果类型

    在Slick官方文档中描述:连接后台数据库后,需要通过定义Projection,即def * 来进行具体库表列column的选择和排序.通过Projection我们可以选择库表中部分列.也可以增加一些 ...

  7. Javaweb项目框架搭建-准备篇

    前言Java从大二开始学习到现在大四也有差不多两年了,但是由于之前一直在玩,没有认真学过,直到现在才开始重新学习.也是很凑巧,看到了黄勇老师的<架构探险>,于是便开始学习写Java Web ...

  8. 每天一个设计模式-3 适配器模式(Adapteer)

    每天一个设计模式-3 适配器模式(Adapteer) 1.现实中的情况 旧式电脑的硬盘是串口的,直接与硬盘连接,新硬盘是并口的,显然新硬盘不能直接连在电脑上,于是就有了转接线.好了,今天的学习主题出来 ...

  9. UIDatePicker

    UIDatePickerDemo 效果 用法 1.导入文件(CustomDatePickerView.h/.m 和UIView+SetRect.h/.m) 2.在所要用到地方导入头文件  #impor ...

  10. 长按TextField或TextView显示中文的粘贴复制

    首先要确保手机当前系统为中文,只需要在 plist 文件中添加 Localized resources can be mixed = YES 就行了