Share my 0ms solution, recursive C++ code, O(1) space usage and O(n) time complexity


  • 2
    F
    bool isSameTree(TreeNode* p, TreeNode* q) {
            if( p == nullptr || q == nullptr ) return  p == q;
            return (p->val == q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        }

  • 0
    S

    Good to see that
    below code can be reduced to less nuber of line :
    if(p==NULL && q==NULL)
    return true;
    if(p==NULL || q==NULL)
    return false;

    above is same as yours
    if( p == nullptr || q == nullptr ) return p == q;


Log in to reply
 

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