Level order traversal with direction change after every two levels
Last Updated : 11 Jul, 2025
Given a binary tree, the task is to print the level order traversal in such a way that the first two levels are printed from left to right, the next two levels are printed from right to left, then the next two from left to right and so on. So, the problem is to reverse the direction of the level order traversal of the binary tree after every two levels.
Examples:
Input:
Output: 5 3 7 8 6 4 2 0 1 5 9
Explanation: In the above example, first two levels are printed from left to right, next two levels are printed from right to left.
[Expected Approach - 1] Using Iteration - O(n) Time and O(n) Space
The idea is to make use of queue and stack here. Queue is used for performing normal level order traversal. Stack is used for reversing the direction of traversal after every two levels.
While doing normal level order traversal, first two levels nodes are stored at the time when they are popped out from the queue. For the next two levels, we push the node values onto a stack, allowing us to later retrieve them in right-to-left order. This alternating pattern continues until all nodes have been processed. At the end of each level, we check the direction:
if we traversed left to right, we simply append the collected values to our final result.
if right to left, we pop values from the stack and then append them.
Below is the Implementation of the above approach:
C++
// C++ implementation to find Level order traversal// with direction change every 2 Levels using // Stack + Queue#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to perform modified level-order traversalvector<vector<int>>modifiedLevelOrderTraversal(Node*root){vector<vector<int>>result;if(!root)returnresult;// Queue to store the nodesqueue<Node*>q;q.push(root);boolleftToRight=true;intlevelCounter=0;while(!q.empty()){intsize=q.size();vector<int>level;// Stack to reverse the level if neededstack<int>s;for(inti=0;i<size;++i){Node*curr=q.front();q.pop();if(leftToRight){level.push_back(curr->data);}else{s.push(curr->data);}if(curr->left)q.push(curr->left);if(curr->right)q.push(curr->right);}// If traversing from right to left, pop from stackif(!leftToRight){while(!s.empty()){level.push_back(s.top());s.pop();}}result.push_back(level);levelCounter++;// Toggle direction after every two levelsif(levelCounter%2==0){leftToRight=!leftToRight;}}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);vector<vector<int>>result=modifiedLevelOrderTraversal(root);print2DArray(result);return0;}
Java
// Java implementation to find Level order traversal// with direction change every 2 Levels using // Stack + Queueimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}// Function to perform modified level-order traversalclassGfG{staticList<List<Integer>>modifiedLevelOrderTraversal(Noderoot){List<List<Integer>>result=newArrayList<>();if(root==null)returnresult;// Queue to store the nodesQueue<Node>q=newLinkedList<>();q.add(root);booleanleftToRight=true;intlevelCounter=0;while(!q.isEmpty()){intsize=q.size();List<Integer>level=newArrayList<>();Stack<Integer>s=newStack<>();for(inti=0;i<size;i++){Nodecurr=q.poll();if(leftToRight){level.add(curr.data);}else{s.push(curr.data);}if(curr.left!=null)q.add(curr.left);if(curr.right!=null)q.add(curr.right);}if(!leftToRight){while(!s.isEmpty()){level.add(s.pop());}}result.add(level);levelCounter++;// Toggle direction after every two levelsif(levelCounter%2==0){leftToRight=!leftToRight;}}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);List<List<Integer>>result=modifiedLevelOrderTraversal(root);print2DArray(result);}}
Python
# Python implementation to find Level order traversal# with direction change every 2 Levels using # Stack + QueuefromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to perform modified level-order# traversaldefmodified_level_order_traversal(root):result=[]ifnotroot:returnresult# Queue to store the nodesq=deque([root])left_to_right=Truelevel_counter=0whileq:size=len(q)level=[]s=[]for_inrange(size):curr=q.popleft()ifleft_to_right:level.append(curr.data)else:s.append(curr.data)ifcurr.left:q.append(curr.left)ifcurr.right:q.append(curr.right)ifnotleft_to_right:whiles:level.append(s.pop())result.append(level)level_counter+=1# Toggle direction after every two levelsiflevel_counter%2==0:left_to_right=notleft_to_rightreturnresultdefprint_2d_array(arr):forrowinarr:print(" ".join(map(str,row)))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)result=modified_level_order_traversal(root)print_2d_array(result)
C#
// C# implementation to find Level order traversal// with direction change every 2 Levels using // Stack + QueueusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Function to perform modified level-order traversalstaticList<List<int>>ModifiedLevelOrderTraversal(Noderoot){List<List<int>>result=newList<List<int>>();if(root==null)returnresult;// Queue to store the nodesQueue<Node>q=newQueue<Node>();q.Enqueue(root);boolleftToRight=true;intlevelCounter=0;while(q.Count>0){intsize=q.Count;List<int>level=newList<int>();Stack<int>s=newStack<int>();for(inti=0;i<size;i++){Nodecurr=q.Dequeue();if(leftToRight){level.Add(curr.data);}else{s.Push(curr.data);}if(curr.left!=null)q.Enqueue(curr.left);if(curr.right!=null)q.Enqueue(curr.right);}if(!leftToRight){while(s.Count>0){level.Add(s.Pop());}}result.Add(level);levelCounter++;// Toggle direction after every// two levelsif(levelCounter%2==0){leftToRight=!leftToRight;}}returnresult;}staticvoidPrint2DArray(List<List<int>>arr){foreach(varrowinarr){foreach(varvalinrow){Console.Write(val+" ");}Console.WriteLine();}}staticvoidMain(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);List<List<int>>result=ModifiedLevelOrderTraversal(root);Print2DArray(result);}}
JavaScript
// JavaScript implementation to find Level order traversal// with direction change every 2 Levels using // Stack + QueueclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to perform modified level-order traversalfunctionmodifiedLevelOrderTraversal(root){constresult=[];if(!root)returnresult;// Queue to store the nodesconstq=[];q.push(root);letleftToRight=true;letlevelCounter=0;while(q.length>0){constsize=q.length;constlevel=[];consts=[];for(leti=0;i<size;i++){constcurr=q.shift();if(leftToRight){level.push(curr.data);}else{s.push(curr.data);}if(curr.left)q.push(curr.left);if(curr.right)q.push(curr.right);}if(!leftToRight){while(s.length>0){level.push(s.pop());}}result.push(level);levelCounter++;// Toggle direction after every two levelsif(levelCounter%2===0){leftToRight=!leftToRight;}}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);constresult=modifiedLevelOrderTraversal(root);print2DArray(result);
Output
1
2 3
6 5 4
[Expected Approach 2] Using Recursion - O(n) Time and O(n) Space
The idea is to use a recursive method to print nodes level by level. For each level, check the traversal direction using a flag. If the flag is true, print nodes from right to left. If false, print nodes from left to right. Initially, the flag is set to false and changes every two levels to alternate the direction.