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

    链接: http://leetcode.com/problems/closest-binary-search-tree-value/

    3/5/2017

    出现的问题:

    1. 这道题绝对不是把minH, maxL设为Integer最大最小值就可以了。因为有可能target就是很接近这两个值的double值,得出错的结果。

    2. 当minH, maxL有一个为null的时候,返回另外一个值。都不为null时再比较绝对值。

     1 public class Solution {
     2     public int closestValue(TreeNode root, double target) {
     3         Integer minH = null;
     4         Integer maxL = null;
     5         
     6         while (root != null) {
     7             if (root.val > target) {
     8                 if (minH == null || root.val < minH) minH = root.val;
     9                 root = root.left;
    10             } else {
    11                 if (maxL == null || root.val > maxL) maxL = root.val;
    12                 root = root.right;
    13             }
    14         }
    15         if (minH == null) return maxL;
    16         else if (maxL == null) return minH;
    17         return target - maxL < minH - target? maxL: minH;
    18     }
    19 }

    别人的做法更好,只需要一个minDiff就可以了,并且minDiff可以初始化为root.val,简化非常多。

  • 相关阅读:
    react-redux
    Vue中常用的UI框架
    vue中router与route的区别
    H5新增input属性
    H5新增的input类型
    菜鸡对作用域链的理解
    自己对路由的一些理解
    浏览器缓存
    黄瓜的不定期更新面试题
    ajax封装
  • 原文地址:https://www.cnblogs.com/panini/p/6508039.html
Copyright © 2011-2022 走看看