binary tree zig zag level order traversal fast ,neat and simple code in c++
    vector<vector<int>> fn(TreeNode* root) {
//         if null
        if(!root) return vector<vector<int> >();
		
        // for bfs
        queue<TreeNode*>q;
        q.push(root);
		
        // for maintaing the zig zag order
        bool order=true;
        
		// final resulting vector
        vector<vector<int> >res;
        
        int j=0;
        
        while(!q.empty()){
                    
//             storing current level nodes in temp vector
            int cnt = q.size();
            vector<int>temp;
			
            while(cnt--){
                
                auto node = q.front();
                q.pop();
                
                temp.push_back(node->val);
                
//             pushing left and right nodes
                if(node->left){
                    q.push(node->left);
                }
                if(node->right){
                    q.push(node->right);
                }
            }
            
//             storing in res vector in req order    
            cnt = temp.size();
            res.push_back(vector<int>());
            
            if(order){
                for(int i=0;i<cnt;i++){
                    res[j].push_back(temp[i]);
                }
                order = false;
            }
            else{
                for(int i=cnt-1;i>=0;i--){
                    res[j].push_back(temp[i]);
                }
                order = true;
            }
            
            j++;
            temp.clear();
            
        }
        
        return res;
        
    }
	```
Comments (0)