Simple iterative Java solution with explaination

  • 16
    public int closestValue(TreeNode root, double target) {
            int closestVal = root.val; 
            while(root != null){ 
                //update closestVal if the current value is closer to target
                closestVal = (Math.abs(target - root.val) < Math.abs(target - closestVal))? root.val : closestVal;
                if(closestVal == target){   //already find the best result
                    return closestVal;
                root = (root.val > target)? root.left: root.right;   //binary search
            return closestVal;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.