zoukankan      html  css  js  c++  java
  • [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.

    Example:

    Input: root = [4,2,5,1,3], target = 3.714286
    
        4
       / 
      2   5
     / 
    1   3
    
    Output: 4

    最接近的二叉搜索树的值。题意是给一个二叉树和一个target值(会是一个浮点数),请找出二叉树里面val最接近这个target的node。

    递归的思路我没有想得非常清楚所以我这里只给出迭代的做法。因为是BST所以会简单很多,根据target与root节点比较的大小情况来决定到底往左子树走还是往右子树走。

    时间O(logn) - 因为每次只会往树的一边走

    空间 - O(1)

    Java实现

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

    JavaScript实现

     1 /**
     2  * @param {TreeNode} root
     3  * @param {number} target
     4  * @return {number}
     5  */
     6 var closestValue = function (root, target) {
     7     let res = root.val;
     8     while (root !== null) {
     9         if (Math.abs(root.val - target) < Math.abs(res - target)) {
    10             res = root.val;
    11         }
    12         root = root.val > target ? root.left : root.right;
    13     }
    14     return res;
    15 };

    LeetCode 题目总结

  • 相关阅读:
    《机器学习实战》K近邻算法
    第 4 章 单例模式
    第 3 章 闭包和高阶函数
    第2章 this 、 call 和 apply
    第1章 面向对象的JavaScript
    前言 发展历史
    Linux常用的基本命令
    VLSM
    IP编址和子网划分
    RADIUS操作命令
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12537404.html
Copyright © 2011-2022 走看看