Why does my Java solution get a NullPointerException?


  • 0
    F
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isValidBST(TreeNode root) {
            if(root==null){
                return true;
            }
            if(root.val>Long.MIN_VALUE && root.val<Long.MAX_VALUE){
                if(root.left.val < root.val && root.right.val>root.val){ //get java.lang.NullPointerException here
                    isValidBST(root.left);
                    isValidBST(root.right);
                }
            }
            return false;
        }
    }

  • 0
    L

    If "root" is a leaf node, root.left and root.right are certainly both null. Thus, "null.val" gives you NPE.


Log in to reply
 

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