270. Closest Binary Search Tree Value

// compare current result  with every root 
class Solution {
    public int closestValue(TreeNode root, double target) {
        int result = root.val;
        
        while(root != null){
            if(root.val > target){
                if(Math.abs(result - target) > Math.abs(root.val - target)){
                    result = root.val;
                }
                root = root.left;
            }else{
                if(Math.abs(result - target) > Math.abs(root.val - target)){
                    result = root.val;
                }
                root = root.right;
            }
        }
        return result;

    }
}

 

 

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


idea:
 注意先保存下 第一个root的value, 因为这个root 的 value 也有可能是 最好的值
不停移动root直到走到底。

if target < root, move to the left, 

if target > root, move to the right 

 

at every root, compare the result with the current root value, who is closer to the target, if current root value is closer, update the result


give target is a floating, and all the elements in the tree are integers . so there is no way the target number is
equal to any elements in the tree. so there is only two cases , the target is either bigger than the current root val,
or smaller.

 

 

posted on 2018-08-09 18:25  猪猪&#128055;  阅读(100)  评论(0)    收藏  举报

导航