Clean Java Solution

  • 0
    public int closestValue(TreeNode root, double target) {
        if (root == null)
            return -1;
        if (root.left == null && root.right == null)
            return root.val;
        if (root.val == target)
            return root.val;
        int closest;
        if (target > root.val) 
            closest = closestValue(root.right, target);
            closest = closestValue(root.left, target);
        if (closest == target) return closest;
        if (closest == -1) return root.val;
        if (Math.abs(closest - target) < Math.abs(root.val - target))
            return closest;
            return root.val;

Log in to reply

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