c++ recursive && iterative solutions


  • 0
    B

    recursive solution

    bool ismirror(TreeNode *p, TreeNode *q){
            if(!p&&!q) return true;
            else if(!p||!q) return false;
            
            if(p->val==q->val) return ismirror(p->left,q->right) && ismirror(p->right,q->left);
            else return false;
        }
    
        bool isSymmetric(TreeNode* root) {
            if(!root) return true;
            
            return ismirror(root->left, root->right);
        }
    

    iterative solution

        bool ismirror(TreeNode *p, TreeNode *q){
            if(!p&&!q) return true;
            else if(!p||!q) return false;
            
            if(p->val!=q->val) return false;
            else return true;
        }
        
        bool isSymmetric(TreeNode* root) {
            if(!root) return true;
            queue<TreeNode*> l,r;
            l.push(root->left);
            r.push(root->right);
            
            while(!l.empty() && !r.empty()){
                TreeNode *p=l.front(), *q=r.front();
                l.pop();
                r.pop();
                if(!p&&!q) continue;
                if(!ismirror(p,q)) return false;
                
                l.push(p->left);
                r.push(q->right);
                l.push(p->right);
                r.push(q->left);
            }
            
            return true;
        }
    

Log in to reply
 

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