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,简化非常多。

posted @ 2017-03-06 07:01  panini  阅读(160)  评论(0编辑  收藏  举报