8ms accepted C++ solution, with 2 queues.


  • 0
    D
     class Solution {
    public:
    bool isSymmetric(TreeNode* root) {
     queue<TreeNode *> q;
     queue<TreeNode *> rev_q;
     
     if(root==NULL||root->left==NULL && root->right==NULL)
        return true;
        
     q.push(root);
     rev_q.push(root);
     
     while(!q.empty() && !rev_q.empty())
        {
            if(q.front()==NULL && rev_q.front()!=NULL||q.front()!=NULL && rev_q.front()==NULL)
                return false;
            else if(q.front()!=NULL && rev_q.front()!=NULL && q.front()->val!=rev_q.front()->val)
                return false;
                
            if(q.front()!=NULL)
                {
                    q.push(q.front()->left);
                    q.push(q.front()->right);
                }
            if(rev_q.front()!=NULL)
                {
                rev_q.push(rev_q.front()->right);
                rev_q.push(rev_q.front()->left);
                }
            q.pop();
            rev_q.pop();
        }
        
        if(rev_q.empty()&&q.empty())
            return true;
        else 
            return false;
    
    }
    };

Log in to reply
 

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