Why I got a "Runtime Error : Null Pointer Exception " when i consider the case of 'null'


  • 0
    C

    I got this message

    Runtime Error Message:	Line 20: java.lang.NullPointerException
    Last executed input:	{}
    

    The line 20 is the first line of function validateBST.

    when i write the code like this :

    public boolean isValidBST(TreeNode root) {
        if(root == null){
            return true;
        }
        return (root.left == null ? true : validateBST(root.left , Integer.MIN_VALUE , root.val))
                && (root.right == null ? true : validateBST(root.right , root.val , Integer.MAX_VALUE));
    }
    
    public boolean validateBST(TreeNode root , int down , int up){
        if(root.val <= down || root.val >= up)
            return false;
        if(root.left == null && root.right == null)
            return true;
        return root.left == null ? true : validateBST(root.left , down , root.val)
                && root.right == null ? true : validateBST(root.right , root.val , up);
    }
    

    But when i change the code:

    public boolean isValidBST(TreeNode root) {
        if(root == null){
            return true;
        }
        boolean flag1,flag2;
        flag1 = root.left == null ? true : validateBST(root.left , Long.MIN_VALUE , root.val);
        flag2 = root.right == null ? true : validateBST(root.right , root.val , Long.MAX_VALUE);
        return flag1 && flag2;
    }
    
    public boolean validateBST(TreeNode root , long down , long up){
        if(root.val <= down || root.val >= up)
            return false;
        if(root.left == null && root.right == null)
            return true;
        boolean flag1,flag2;
        flag1 = root.left == null ? true : validateBST(root.left , down , root.val);
        flag2 = root.right == null ? true : validateBST(root.right , root.val , up);
        return flag1 && flag2;
    }
    

    I got an AC .

    Those two codes run well in my eclipse.


  • 0
    Y

    It seems that happens in every problem if you use java. Leetcode says there is a bug in a recent change, I don't know if it's the reason.


  • 0
    C

    I think that's the reason.
    The error message is not always correct in Leetcode recently.
    Do you know where Leetcode declare the bug message ?
    Oh, almost fogot,thank you for answering:)


Log in to reply
 

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