Last executed input:{}, what happened to my code?


  • 0
    L

    My C++ code below got the Runtime Error, with last executed input {}. but anothor code similar is accepted,why it happened? Please

    This is the C++ code which is wrong:

    int maxDepth(TreeNode *root) {
        int depth;
        if(root==NULL)  depth = 0;
        
        int leftDepth=maxDepth(root->left);
        int rightDepth=maxDepth(root->right);
        depth = (leftDepth>rightDepth ) ? (leftDepth+1):(rightDepth+1);
        
        return depth;
    }
    

    This is the accepted one:

       int maxDepth(TreeNode *root) 
       {    
             if(root==NULL)  return 0;
    
        int leftDepth=maxDepth(root->left);
        int rightDepth=maxDepth(root->right);
        return (leftDepth>rightDepth ) ? (leftDepth+1):(rightDepth+1);
       }

  • 2
    M

    In the first try, you store the depth as 0, but then try to get the children of a null node, which raises an exception.

    In the second, you've returned the zero value, so it never reaches that point. It just returns zero without having to access an instance variable of a null object.


  • 0
    S

    In other words, you forgot to follow your "if" with an "else".


Log in to reply
 

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