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. 基于Java+Selenium的WebUI自动化测试框架(一)---页面元素定位器

    对于自动化测试,尤其是UI的自动化测试.是很多做黑盒功能测试的同学,入门自动化测试一个最为直观的或者说最容易理解的途径之一. 对于手工测试和自动化测试的优劣,网上有很多论述,在这里不作展开讨论.但是, ...

  2. Kotlin调用Java程序解析

    Kotlin跟Java是百分百兼容的,换言之,也就是它们俩是可以互操作的,也就是Java可以调Kotlin,Koltin可以调Java,所以下面来看一下在Kotlin中如何来调用Java代码: 咱们来 ...

  3. C#WinForm无边框窗体移动----模仿鼠标单击标题栏移动窗体位置

    C#WinForm无边框窗体移动方法.模仿鼠标单击标题栏移动窗体位置 这里介绍俩种办法 方法一:直接通过修改窗体位置从而达到移动窗体的效果 方法二:直接伪装发送单击任务栏消息,让应用程序误以为单击任务 ...

  4. 七牛云——qshell一个神奇的工具

    前言 qshell是利用七牛文档上公开的API实现的一个方便开发者测试和使用七牛API服务的命令行工具.该工具设计和开发的主要目的就是帮助开发者快速解决问题.目前该工具融合了七牛存储,CDN,以及其他 ...

  5. js去除数组中重复的数字

    var arr = [2,1,4,3,2,4,2,3,4,2,6,5,5] var obj = {}; var arrNew = []; for(var i=arr.length-1;i>=0; ...

  6. ReactiveX 学习笔记(30)操作符辨析

    RxJava: merge/concat/switch RxJS: merge/concat/switch/exhaust RxSwift: merge/concat/switchLatest mer ...

  7. Scanner的常用用法

    通过new Scanner(System.in)创建一个Scanner,控制台会一直等待输入,直到敲回车键结束,把所输入的内容传给Scanner. s.useDelimiter(" |,|\ ...

  8. LG1378

    题目描述 在一个长方形框子里,最多有N(0≤N≤6)个相异的点,在其中任何一个点上放一个很小的油滴,那么这个油滴会一直扩展,直到接触到其他油滴或者框子的边界.必须等一个油滴扩展完毕才能放置下一个油滴. ...

  9. HTTP协议(待写)

    先来了解了解 TCP/IP TCP/IP(Transmission Control Protocol / Internet Protocol)是计算机通讯必须遵守的规则,是不同的通信协议的大集合,其里 ...

  10. learning scala akka actorySystem create and close

    package com.example import akka.actor.ActorSystem import scala.util.{Failure, Success} import scala. ...