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. nginx简易教程

    概述 什么是nginx? Nginx (engine x) 是一款轻量级的Web 服务器 .反向代理服务器及电子邮件(IMAP/POP3)代理服务器. 什么是反向代理? 反向代理(Reverse Pr ...

  2. AJAX(一)

    AJAX(一) Ajax是Asynchronous Javascript和XML的简写,这一技术能够向服务器请求额外的数据而无需卸载页面,会带来更好的用户体验. [前面的基础知识][关于同步和异步的了 ...

  3. php内核分析(四)-do_cli

    这里阅读的php版本为PHP-7.1.0 RC3,阅读代码的平台为linux # main 把剩下的代码增加了下注释全部贴出来了(这个是简化后的main函数,去掉了一些无关紧要的代码段): int m ...

  4. Ionic2系列——使用DeepLinker实现指定页面URL

    Ionic2使用了近似原生App的页面导航方式,并不支持Angular2的路由.这种方式在开发本地App的时候比较方便,但如果要用来开发纯Web页面就有点问题了,这种情况下Angular2的route ...

  5. 用c-free 5写一个入门的程序

    本文记录了在windows系统中使用C-FREE 5新建一个Hello HoverTree程序的步骤. 安装好C-Free 5之后,打开.新建一个工程: 附C-Free 5下载:http://hove ...

  6. ASP.Net MVC Session和Cookies的简单使用

    目标:用Session和Cookies实现登陆信息保存和展现 Cookies实现: Controller: //把登陆用户名存到cookies中 HttpCookie cook = new HttpC ...

  7. asp.net MVC4——省市三级联动

    controller: public ActionResult GetCity(string id) { AreaService _areaSvc = new AreaService(); List& ...

  8. 【Effective Java】9、使用EnumMap代替序数索引

    package cn.xf.cp.ch02.item33; import java.util.EnumMap; import java.util.HashSet; import java.util.M ...

  9. ASP.NET MVC企业级实战目录

    电子书样稿 (关注最新进度,请加QQ群:161436236) ASP.NET MVC企业实战第1章 MVC开发前奏.pdf ASP.NET MVC企业实战第10章 站内搜索.pdf 已经好长一段时间没 ...

  10. WebService 概念和工作原理(一)

    今天我们一起来学习WebService.它到底是干啥用的? Web service是一个平台独立的,低耦合的,自包含的.基于可编程的web的应用程序,可使用开放的XML(标准通用标记语言下的一个子集) ...