4ms with 2 queues


  • 0
    D
    class Solution {
        public:
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector< vector<int> > result;
        vector<int> row;
        queue<TreeNode *> q;
        queue<TreeNode *> q1;
        int count=1;
        int flip=1;
        
        if(root==NULL) return {};
        q.push(root);
        q1.push(root);
        
        while(!q.empty())
        {
            if(flip%2!=0){
                if(q1.front()->right)q.push(q1.front()->right);
                if(q1.front()->left)q.push(q1.front()->left);
                if(q.front()->left)q1.push(q.front()->left);
                if(q.front()->right)q1.push(q.front()->right);
                q1.pop();
            }
            else
            {
                if(q1.front()->left)q.push(q1.front()->left);
                if(q1.front()->right)q.push(q1.front()->right);
                if(q.front()->right)q1.push(q.front()->right); 
                if(q.front()->left)q1.push(q.front()->left);   
                q1.pop();
            }
            row.push_back(q.front()->val);
            q.pop();
            
            if(--count==0)
                {
                 result.push_back(row);
                 row.clear();
                 count=q.size();
                 flip++;
                }
            
        }
        return result;
    }
    

    };


Log in to reply
 

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