NullPointerExceptiokn


  • 0
    K
    public class Solution {
    public int maxDepth(TreeNode root) {
        
        int leftVal = 0;
        int rightVal = 0;
        
        if(root.left != null)
        {
            TreeNode left = root.left;
            left.val = root.val + 1;
            leftVal = maxDepth(left);
        }
        
        if(root.right != null)
        {
            TreeNode right = root.right;
            right.val = root.val + 1;
            rightVal = maxDepth(right);
        }
        
        if(root.left == null && root.right == null)
        {
            return root.val;
        }
        
        if(leftVal > rightVal)
        {
            return leftVal;
        }
        else
        {
            return rightVal;
        }
        
    }
    

    }

    it gives me NullPointerException, WHY????


  • 0
    X

    I guess root maybe null!
    I write it using CPP.

    int maxDepth(TreeNode *root) {
    if (root == NULL) return 0;

        int left = maxDepth(root->left);
        int right = maxDepth(root->right);
    
        return left > right ? 1 + left : 1 + right;
    

    }


Log in to reply
 

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