Java recursive, attention to (int) cast problem


  • 0
    P
    public int closestValue(TreeNode root, double target) {
        if(root.val < target && root.right != null)
        {
            int rightClosest = closestValue(root.right, target);
            return Math.abs(rightClosest - target) > Math.abs(root.val - target) ? root.val : rightClosest;
        }
        else if(root.val > target && root.left != null)
        {
            int leftClosest = closestValue(root.left, target);
            return Math.abs(leftClosest - target) > Math.abs(root.val - target) ? root.val : leftClosest;
        }
        
        return root.val;
    }
    

    can not check(int) target == root.val here first, (int) will cast down the target value;


Log in to reply
 

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