C two step solution


  • 0
    C

    Just check if the tree node s is the same with t, if not , check the left sub-tree and the right tree.

    bool isSame (struct TreeNode* s, struct TreeNode* t) {
        if (!s && !t)
            return true;
        if (!s || !t)
            return false;
        if (s->val != t->val)
            return false;
        return isSame (s->left, t->left) && isSame (s->right, t->right);
    } 
    
    bool isSubtree(struct TreeNode* s, struct TreeNode* t) {
        if (!s)
            return false;
        if (!t)
            return true;
        if (isSame(s, t))
            return true;
        return isSubtree(s->left, t) || isSubtree(s->right, t);
    }
    

Log in to reply
 

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