[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 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 最近的二叉搜索树的值的更多相关文章
- [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 ...
- [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 ...
- [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 ...
- 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 ...
- [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 ...
- 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 ...
- 109 Convert Sorted List to Binary Search Tree 有序链表转换二叉搜索树
给定一个单元链表,元素按升序排序,将其转换为高度平衡的BST.对于这个问题,一个高度平衡的二叉树是指:其中每个节点的两个子树的深度相差不会超过 1 的二叉树.示例:给定的排序链表: [-10, -3, ...
- Leetcode109. Convert Sorted List to Binary Search Tree有序链表转换二叉搜索树
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树. 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1. 示例: 给定的有序链表: [-10 ...
- [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 ...
随机推荐
- drf框架总结复习(1)
Serializers 序列化组件 为什么要用序列化组件 当我们做前后端分离的项目~~我们前后端交互一般都选择JSON数据格式,JSON是一个轻量级的数据交互格式. 那么我们给前端数据的时候都要转成j ...
- 《Java周边》vue开发环境搭建(windows)
1. NodeJs 安装包下载 百度云:链接: https://pan.baidu.com/s/169TdKRLZd0dXbKSGTr8evw 提取码: th4a 复制这段内容后打开百度网盘手机App ...
- WebService(一)
最近一段时间研究webservice,一般来说,开发java的Webservice经常使用axis2和cxf这两个比较流行的框架 先使用cxf,开发一个完整示例,方便对webservice有一个整体的 ...
- 使用mybatis框架实现带条件查询-多条件(传入实体类)
在实际的项目开发中,使用mybatis框架查询的时候,不可能是只有一个条件的,大部分情况下是有多个条件的,那么多个条件应该怎样传入参数: 思考: 需求:根据用户姓名(模糊查询),和用户角色对用户表进 ...
- Win如何查看某个端口被谁占用并停掉
第一步在我们的电脑上按win+R键打开运行,输入cmd, 第二步进去命令提示符之后,输入“netstat -ano”,按回车键,查出所有端口,如下图所示: 第三步如果我们想找8089端口,输入nets ...
- Greenplum 资源队列(转载)
1.创建资源队列语法 Command: CREATE RESOURCE QUEUEDescription: create a new resource queue for workload m ...
- 从TEB到PEB再到SEH(二)
什么是SEH? SEH( Structured Exception Handling , 结构化异常处理 ) 结构化异常处理(SEH)是Windows操作系统提供的强大异常处理功能.而Visual C ...
- WinDbg常用命令系列---线程相关操作~*
~ (Thread Status) 波浪符(~)命令显示指定线程或当前进程中所有线程的状态. ~ Thread 参数: Thread指定要显示的线程.如果省略此参数,将显示所有线程. 环境: 模式 仅 ...
- .NET API Gateway Ocelot 介绍
项目:https://github.com/ThreeMammals/Ocelot Windows (AppVeyor) Linux & OSX (Travis) Windows Ma ...
- 点击复制文字到剪贴板兼容性安卓ios
一般那种活动H5分享可能会用到点击复制文字到剪贴板,很简单的功能 于是搜了一搜:js复制文字到剪贴板,可用结果大致分为两类: 一类是js原生方法,这种方法兼容性不好,不兼容ios: https://d ...