Zig-Zag level order traversal of Binary Tree after every K levels
Last Updated : 23 Jul, 2025
Given a binary tree and an integer k, the task is to print the level order traversal in such a way that first k levels are printed from left to right, next k levels are printed from right to left, then next k levels are from left to right and so on.
Examples:
Input: k = 1
Output: 1 3 2 4 5 6 Explanation: In the above example, first level is printed from left to right and the second level is printed from right to left, and then last level is printed from left to right.
Input: k = 3
Output: 20 8 22 4 12 14 10 Explanation: In the above example, first 3 levels are printed from left to right and the last level is printed from right to left
Approach:
The idea is to start performinglevel order traversalon the tree from the left most end. After every k level, change the direction of printing the elements. For this use stack. When the levels are to be printed from the right keep those values in stack and print the stack elements one by one from top. Because of the last in first out property of stack the elements would printed in reverse order.
Follow the steps mentioned below to implement the above idea:
Use queue to perform level order traversal.
In each level:
If it is to be printed from the left, print them and push their child nodes in the queue.
If this level is to be printed from the right side push the elements in a stack and print them after the whole level is traversed.
If k levels are covered change the direction of printing from the next one.
C++
// C++ implementation to print ZigZag level order// after every k Levels#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to traverse the tree and store nodes// in a 2D vector by reversing the direction of traversal// after every n levelsvector<vector<int>>traverse(Node*root,intn){vector<vector<int>>result;if(!root)returnresult;// Queue for level order traversalqueue<Node*>q;// Stack for reverse level order traversalstack<Node*>s;boolright2left=false;intcount=0;q.push(root);while(!q.empty()){intsize=q.size();count++;// To store nodes at the current levelvector<int>levelNodes;while(size--){root=q.front();q.pop();// Store nodes from left to rightif(right2left==false){levelNodes.push_back(root->data);}// Push nodes into the stack for// reverse orderelse{s.push(root);}if(root->left)q.push(root->left);if(root->right)q.push(root->right);}// If reversing, store nodes in// reverse orderif(right2left==true){while(!s.empty()){levelNodes.push_back(s.top()->data);s.pop();}}// Add the current level to the resultresult.push_back(levelNodes);// Reverse the direction after n levelsif(count==n){right2left=!right2left;count=0;}}returnresult;}voidprint2DArray(vector<vector<int>>&arr){for(autorow:arr){for(intval:row){cout<<val<<" ";}cout<<endl;}}intmain(){// Binary tree structure://// 1// / \ // 2 3// / \ \ // 4 5 6Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->right=newNode(6);intk=3;vector<vector<int>>result=traverse(root,k);print2DArray(result);return0;}
Java
// Java implementation to print ZigZag level order// after every k Levelsimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Function to traverse the tree and store nodes// in a 2D List by reversing the direction of traversal// after every n levelsstaticList<List<Integer>>traverse(Noderoot,intn){List<List<Integer>>result=newArrayList<>();if(root==null)returnresult;// Queue for level order traversalQueue<Node>q=newLinkedList<>();// Stack for reverse level order traversalStack<Node>s=newStack<>();// For changing the direction of traversalbooleanright2left=false;intcount=0;q.add(root);while(!q.isEmpty()){intsize=q.size();count++;// To store nodes at the current levelList<Integer>levelNodes=newArrayList<>();while(size-->0){root=q.poll();// Store nodes from left to rightif(!right2left){levelNodes.add(root.data);}// Push nodes into the stack for// reverse orderelse{s.push(root);}if(root.left!=null){q.add(root.left);}if(root.right!=null){q.add(root.right);}}// If reversing, store nodes// in reverse orderif(right2left){while(!s.isEmpty()){levelNodes.add(s.pop().data);}}// Add the current level to the resultresult.add(levelNodes);// Reverse the direction after n levelsif(count==n){right2left=!right2left;count=0;}}returnresult;}staticvoidprint2DArray(List<List<Integer>>arr){for(List<Integer>row:arr){for(intval:row){System.out.print(val+" ");}System.out.println();}}publicstaticvoidmain(String[]args){// Binary tree structure://// 1// / \// 2 3// / \ \// 4 5 6Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(6);intk=3;List<List<Integer>>result=traverse(root,k);print2DArray(result);}}
Python
# Python implementation to print ZigZag level order# after every K LevelsfromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to traverse the tree and store nodes# in a 2D list by reversing the direction of traversal# after every n levelsdeftraverse(root,n):result=[]ifnotroot:returnresult# Queue for level order traversalq=deque()# Stack for reverse level # order traversals=[]# For changing the direction of# traversalright2left=Falsecount=0q.append(root)whileq:size=len(q)count+=1# To store nodes at the current levellevel_nodes=[]whilesize>0:root=q.popleft()size-=1# Store nodes from left to rightifnotright2left:level_nodes.append(root.data)# Push nodes into the stack for# reverse orderelse:s.append(root)ifroot.left:q.append(root.left)ifroot.right:q.append(root.right)# If reversing, store nodes in # reverse orderifright2left:whiles:level_nodes.append(s.pop().data)# Add the current level to the resultresult.append(level_nodes)# Reverse the direction after n levelsifcount==n:right2left=notright2leftcount=0returnresultdefprint2DArray(arr):forrowinarr:forvalinrow:print(val,end=" ")print()if__name__=="__main__":# Binary tree structure:## 1# / \# 2 3# / \ \# 4 5 6root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.right=Node(6)k=3result=traverse(root,k)print2DArray(result)
C#
// C# implementation to print ZigZag level order// after every k LevelsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Function to traverse the tree and store nodes// in a 2D list by reversing the direction of traversal// after every n levelsstaticList<List<int>>Traverse(Noderoot,intn){List<List<int>>result=newList<List<int>>();if(root==null)returnresult;// Queue for level order traversalQueue<Node>q=newQueue<Node>();// Stack for reverse level order traversalStack<Node>s=newStack<Node>();// For changing the direction of traversalboolright2left=false;intcount=0;q.Enqueue(root);while(q.Count>0){intsize=q.Count;count++;// To store nodes at the current levelList<int>levelNodes=newList<int>();while(size-->0){root=q.Dequeue();// Store nodes from left to rightif(!right2left){levelNodes.Add(root.data);}else{s.Push(root);}if(root.left!=null)q.Enqueue(root.left);if(root.right!=null)q.Enqueue(root.right);}// If reversing, store nodes in// reverse orderif(right2left){while(s.Count>0){levelNodes.Add(s.Pop().data);}}// Add the current level to the resultresult.Add(levelNodes);// Reverse the direction after n levelsif(count==n){right2left=!right2left;count=0;}}returnresult;}staticvoidPrint2DArray(List<List<int>>arr){foreach(varrowinarr){foreach(intvalinrow){Console.Write(val+" ");}Console.WriteLine();}}staticvoidMain(){// Binary tree structure://// 1// / \// 2 3// / \ \// 4 5 6Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(6);intk=3;List<List<int>>result=Traverse(root,k);Print2DArray(result);}}
JavaScript
// Javascript implementation to print ZigZag level order// after every k LevelsclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to traverse the tree and store nodes// in a 2D array by reversing the direction of traversal// after every n levelsfunctiontraverse(root,n){constresult=[];if(!root)returnresult;// Queue for level order traversalconstq=[];// Stack for reverse level order traversalconsts=[];// For changing the direction of traversalletright2left=false;letcount=0;q.push(root);while(q.length>0){constsize=q.length;count++;// To store nodes at the current levelconstlevelNodes=[];for(leti=0;i<size;i++){constnode=q.shift();// Store nodes from left to rightif(!right2left){levelNodes.push(node.data);}else{s.push(node);}if(node.left)q.push(node.left);if(node.right)q.push(node.right);}// If reversing, store nodes in // reverse orderif(right2left){while(s.length>0){levelNodes.push(s.pop().data);}}// Add the current level to the resultresult.push(levelNodes);// Reverse the direction after n levelsif(count===n){right2left=!right2left;count=0;}}returnresult;}functionprint2DArray(arr){for(constrowofarr){console.log(row.join(' '));}}// Binary tree structure:// // 1// / \// 2 3// / \ \// 4 5 6letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(6)constk=3;constresult=traverse(root,k);print2DArray(result);
Output
1
2 3
4 5 6
Time Complexity: O(n), where n is the total number of nodes in the tree. Each node is visited once during traversal. Auxiliary Space : O(n), due to the space used by the queue and stack.