C++ recursion solution with comments


  • 0
    W
    class Solution {
    public:
        bool isSameTree(TreeNode* p, TreeNode* q) {
        
        if(p==NULL && q==NULL)
            return true;
        else if(p==NULL || q==NULL) //one of p and q is NULL
            return false;
            
        //p!=NULL && q!=NULL
        if(p->val==q->val)
        {
            if(!isSameTree(p->left,q->left))
                return false;
            if(!isSameTree(p->right,q->right))
                return false;
            //above 2 if mean: subtrees of p and q are not same
    
            return true; //p->val == q->val && subtrees of p and q are same
        }
        //p->val != q->val
        return false;
    }
    };

Log in to reply
 

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