Sunday, November 22, 2015

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.
Solution: binary search
Run time complexity is O(logn), constant space.
注意:初始化 minDiff时候不能等于Integer.MAX_VALUE, 
test case: input[1500000000,1400000000], target -1500000000.0 过不了,因为最小差值超过Integer.MAX_VALUE了已经。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int closestValue(TreeNode root, double target) {
        if (root == null) {
            return 0;
        }
        
        double minDiff = Math.abs(root.val - target);
        int value = root.val;
        while (root != null) {
            if (Math.abs(root.val - target) < minDiff) {
                minDiff = Math.abs(root.val - target);
                value = root.val;
            }
            
            if (root.val < target) {
                root = root.right;
            } else {
                root = root.left;
            }
        }
        
        return value;
    }
}

No comments:

Post a Comment