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:

  1. public int closestValue(TreeNode root, double target) {
  2. double min=Double.MAX_VALUE;
  3. int result = root.val;
  4.  
  5. while(root!=null){
  6. if(target>root.val){
  7.  
  8. double diff = Math.abs(root.val-target);
  9. if(diff<min){
  10. min = Math.min(min, diff);
  11. result = root.val;
  12. }
  13. root = root.right;
  14. }else if(target<root.val){
  15.  
  16. double diff = Math.abs(root.val-target);
  17. if(diff<min){
  18. min = Math.min(min, diff);
  19. result = root.val;
  20. }
  21. root = root.left;
  22. }else{
  23. return root.val;
  24. }
  25. }
  26.  
  27. return result;
  28. }  

Java:

  1. public class Solution {
  2. int goal;
  3. double min = Double.MAX_VALUE;
  4.  
  5. public int closestValue(TreeNode root, double target) {
  6. helper(root, target);
  7. return goal;
  8. }
  9.  
  10. public void helper(TreeNode root, double target){
  11. if(root==null)
  12. return;
  13.  
  14. if(Math.abs(root.val - target) < min){
  15. min = Math.abs(root.val-target);
  16. goal = root.val;
  17. }
  18.  
  19. if(target < root.val){
  20. helper(root.left, target);
  21. }else{
  22. helper(root.right, target);
  23. }
  24. }
  25. } 

Java: Iteration

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public int closestValue(TreeNode root, double target) {
  12. if (root == null) return 0;
  13. int min = root.val;
  14. while (root != null) {
  15. min = (Math.abs(root.val - target) < Math.abs(min - target) ? root.val : min);
  16. root = (root.val < target) ? root.right : root.left;
  17. }
  18. return min;
  19. }
  20. }

Java: Recursion

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public int closestValue(TreeNode root, double target) {
  12. TreeNode child = target < root.val ? root.left : root.right;
  13. if (child == null) {
  14. return root.val;
  15. }
  16. int childClosest = closestValue(child, target);
  17. return Math.abs(root.val - target) < Math.abs(childClosest - target) ? root.val : childClosest;
  18. }
  19. }

Python: Iteration, Time: O(h), Space: O(1)

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution(object):
  9. def closestValue(self, root, target):
  10. """
  11. :type root: TreeNode
  12. :type target: float
  13. :rtype: int
  14. """
  15. gap = float("inf")
  16. closest = float("inf")
  17. while root:
  18. if abs(root.val - target) < gap:
  19. gap = abs(root.val - target)
  20. closest = root
  21. if target == root.val:
  22. break
  23. elif target < root.val:
  24. root = root.left
  25. else:
  26. root = root.right
  27. return closest.val

C++: Iteration

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. int closestValue(TreeNode* root, double target) {
  13. double gap = numeric_limits<double>::max();
  14. int closest = numeric_limits<int>::max();
  15.  
  16. while (root) {
  17. if (abs(static_cast<double>(root->val) - target) < gap) {
  18. gap = abs(root->val - target);
  19. closest = root->val;
  20. }
  21. if (target == root->val) {
  22. break;
  23. } else if (target < root->val) {
  24. root = root->left;
  25. } else {
  26. root = root->right;
  27. }
  28. }
  29. return closest;
  30. }
  31. }; 

C++: Iteration

  1. class Solution {
  2. public:
  3. int closestValue(TreeNode* root, double target) {
  4. int res = root->val;
  5. while (root) {
  6. if (abs(res - target) >= abs(root->val - target)) {
  7. res = root->val;
  8. }
  9. root = target < root->val ? root->left : root->right;
  10. }
  11. return res;
  12. }
  13. };

C++: Recursion

  1. class Solution {
  2. public:
  3. int closestValue(TreeNode* root, double target) {
  4. int a = root->val;
  5. TreeNode *t = target < a ? root->left : root->right;
  6. if (!t) return a;
  7. int b = closestValue(t, target);
  8. return abs(a - target) < abs(b - target) ? a : b;
  9. }
  10. };

C++: Recursion

  1. class Solution {
  2. public:
  3. int closestValue(TreeNode* root, double target) {
  4. int res = root->val;
  5. if (target < root->val && root->left) {
  6. int l = closestValue(root->left, target);
  7. if (abs(res - target) >= abs(l - target)) res = l;
  8. } else if (target > root->val && root->right) {
  9. int r = closestValue(root->right, target);
  10. if (abs(res - target) >= abs(r - target)) res = r;
  11. }
  12. return res;
  13. }
  14. };  

类似题目:

  

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. 使用python的jira库操作jira的版本单和问题单链接

    操作JIRA的API来实现的. 但感觉比单纯操作API要简单一些. from jira import JIRA from django.conf import settings JIRA_URL = ...

  2. c和c++区别(未整理)

    学习完C语言和c++比较一下他们之间的区别: c++是c语言的基础上开发的一种面向对象的编程语言,应用十分广泛,按理说c++可以编译任何c的程序,但是两者还是有细微的差别. c++在c的基础上添加了类 ...

  3. test20190905 ChiTongZ

    100+22+90=212.前两道题不错,但T3 没什么意义. 围观刘老爷超强 T1 解法. ChiTongZ的水题赛 [题目简介] 我本可以容忍黑暗,如果我不曾见过太阳. 考试内容略有超纲,不超纲的 ...

  4. django-带参数路由

    路由urls.py from django.conf.urls import url from goods.views import IndexView, DetailView, ListView u ...

  5. App版本更新接口的设计

    前段时间公司业务调整,新开了新的移动端的项目,所以和朋友聊到了“版本号”和“版本更新所需的数据表设计”. 一般来讲大部分的软件版本号分3段,比如 A.B.C A 表示大版本号,一般当软件整体重写,或出 ...

  6. 全局异常捕获处理-@ControllerAdvice+@HandleException

    涂涂影院管理系统这个demo中有个异常管理的标签,用于捕获 涂涂影院APP用户异常信息 ,有小伙伴好奇,排除APP,后台端的是如何处理全局异常的,故项目中的实际应用已记之. 关于目前的异常处理 在使用 ...

  7. Time Frequency (T-F) Masking Technique

    时频掩蔽技术. 掩蔽效应 声掩蔽(auditory masking)是指一个声音的听阈因另一个声音的存在而上升的现象.纯音被白噪声所掩蔽时,纯音听阈上升的分贝数,主要决定于以纯音频率为中心一个窄带噪声 ...

  8. 查看.NET应用程序中的异常(下)

    为什么要使用内存转储进行调试? 在两种主要情况下,您可能需要使用内存转储进行调试.第一种情况是应用程序有一个未处理的异常并崩溃,而您只有一个内存转储.第二种情况是,在生产环境中出现异常或特定行为,并且 ...

  9. mov offset和lea的区别

    mov offset和lea的区别  原文地址:https://www.cnblogs.com/fanzi2009/archive/2011/11/29/2267725.html 全局变量取地址用mo ...

  10. nexus 3.17.0 做为golang 的包管理工具

    nexus 3.17.0 新版本对于go 包管理的支持是基于go mod 的,同时我们也需要一个athens server 然后在nexus 中配置proxy 类型的repo 参考配置 来自官方的配置 ...