BiruLyu
8/4/2017 - 5:35 AM

270. Closest Binary Search Tree Value(#).java

/**
 * 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) {
        int res = root.val;
        double diff = Double.MAX_VALUE;
        while(root != null) {
            if(root.val == target) return root.val;
            double curr = Math.abs(root.val - target);
            if(curr < diff) {
                res = root.val;
                diff = curr;
            }
            if(root.val > target) root = root.left;
            else root = root.right;
        }
        return res;
    }
}
/**
 * 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) {
        int a = root.val;
        TreeNode kid = target < a ? root.left : root.right;
        if (kid == null) return a;
        int b = closestValue(kid, target);
        return Math.abs(a - target) < Math.abs(b - target) ? a : b;
    }
}