0 ms C solution


  • 4
    X
    bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
    if(p == NULL && q == NULL) 
        return true;
    if(p != NULL && q == NULL) 
        return false;
    if(p == NULL && q != NULL) 
        return false;
    if(p->val != q->val)
        return false;
    return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
    }

  • 0
    C

    Hi, my code is like this:
    if(p == NULL && q == NULL)
    return true;
    else if(p->val == q->val)
    return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
    else
    return false;
    the error is runtime error when it comes to [],[0]. Could you explain this error a little bit for me? Thx a ton!


  • 0
    G

    What if p == nullptr and q != nullptr, then your code fails to find p->left (which does not exist) and results in a funtime error.


  • 0
    F

    0ms C solution

    // both of leaf node;
    if (p == NULL && q == NULL)
    {
        return true;
    }
    
    // different structure or value
    if ( (p == NULL && q != NULL)
    || (p != NULL && q == NULL)
    || (p != NULL && q != NULL && p->val != q->val) )
    {
        return false;        
    }
    
    return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    

Log in to reply
 

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