How about return early when find the target value


  • 0
    C
     public int closestValue(TreeNode root, double target) {
    
            TreeNode result = root;
            while(root != null) {
                if(root.val == target) return root.val;
                result = Math.abs(root.val - target) < Math.abs(result.val - target) ? root : result;
                root = root.val > target ? root.left : root.right;
            }
            return result.val;
        }

Log in to reply
 

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