不熟啊Closest value in a binary search tree

mock被考到两遍了
word ladder也是

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int closestValue(TreeNode root, double target) {
        if (root == null || (root.left == null && root.right == null)){
           return root.val;
        }
        double minDiff = Double.MAX_VALUE;
        TreeNode minDiffNode = null;
        TreeNode curt = root;
        while (curt != null){
            double diff = Math.abs(curt.val - target);
            if (diff < minDiff){
                minDiff = diff;
                minDiffNode = curt;
            }
            if (curt.val > target){
                curt = curt.left;                
            } else {
                curt = curt.right;
            }
        }
        return minDiffNode.val;
    }
}

你可能感兴趣的:(不熟啊Closest value in a binary search tree)