Given a binary tree, print the level order traversal in such a way that first two levels are printed from left to right, next two levels are printed from right to left, then next two from left to right and so on. So, the problem is to reverse the direction of level order traversal of binary tree after every two levels.
Examples:
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ / \ / \ / \
8 9 3 1 4 2 7 2
/ / \ \
16 17 18 19
Output:
1
2 3
7 6 5 4
2 7 2 4 1 3 9 8
16 17 18 19
In the above example, first two levels
are printed from left to right, next two
levels are printed from right to left,
and then last level is printed from
left to right.
Approach:
We 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 printed at the time when they are popped out from the queue. For the next two levels, we instead of printing the nodes, pushed them onto the stack. When all nodes of current level are popped out, we print the nodes in the stack. In this way, we print the nodes in right to left order by making use of the stack. Now for the next two levels we again do normal level order traversal for printing nodes from left to right. Then for the next two nodes, we make use of the stack for achieving right to left order.
In this way, we will achieve desired modified level order traversal by making use of queue and stack.
C++
// CPP program to print Zig-Zag traversal // in groups of size 2. #include <iostream> #include <queue> #include <stack> using namespace std; // A Binary Tree Node struct Node { struct Node* left; int data; struct Node* right; }; /* Function to print the level order of given binary tree. Direction of printing level order traversal of binary tree changes after every two levels */void modifiedLevelOrder(struct Node* node) { // For null root if (node == NULL) return; if (node->left == NULL && node->right == NULL) { cout << node->data; return; } // Maintain a queue for normal level order traversal queue<Node*> myQueue; /* Maintain a stack for printing nodes in reverse order after they are popped out from queue.*/ stack<Node*> myStack; struct Node* temp = NULL; // sz is used for storing the count of nodes in a level int sz; // Used for changing the direction of level order traversal int ct = 0; // Used for changing the direction of level order traversal bool rightToLeft = false; // Push root node to the queue myQueue.push(node); // Run this while loop till queue got empty while (!myQueue.empty()) { ct++; sz = myQueue.size(); // Do a normal level order traversal for (int i = 0; i < sz; i++) { temp = myQueue.front(); myQueue.pop(); /*For printing nodes from left to right, simply print the nodes in the order in which they are being popped out from the queue.*/ if (rightToLeft == false) cout << temp->data << " "; /* For printing nodes from right to left, push the nodes to stack instead of printing them.*/ else myStack.push(temp); if (temp->left) myQueue.push(temp->left); if (temp->right) myQueue.push(temp->right); } if (rightToLeft == true) { // for printing the nodes in order // from right to left while (!myStack.empty()) { temp = myStack.top(); myStack.pop(); cout << temp->data << " "; } } /*Change the direction of printing nodes after every two levels.*/ if (ct == 2) { rightToLeft = !rightToLeft; ct = 0; } cout << "\n"; } } // Utility function to create a new tree node Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // Driver program to test above functions int main() { // Let us create binary tree Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(3); root->left->right->right = newNode(1); root->right->left->left = newNode(4); root->right->left->right = newNode(2); root->right->right->left = newNode(7); root->right->right->right = newNode(2); root->left->right->left->left = newNode(16); root->left->right->left->right = newNode(17); root->right->left->right->left = newNode(18); root->right->right->left->right = newNode(19); modifiedLevelOrder(root); return 0; } |
Java
// Java program to print Zig-Zag traversal // in groups of size 2. import java.util.*; class GFG { // A Binary Tree Node static class Node { Node left; int data; Node right; }; /* Function to print the level order of given binary tree. Direction of printing level order traversal of binary tree changes after every two levels */static void modifiedLevelOrder(Node node) { // For null root if (node == null) return; if (node.left == null && node.right == null) { System.out.print(node.data); return; } // Maintain a queue for normal level order traversal Queue<Node> myQueue = new LinkedList<>(); /* Maintain a stack for printing nodes in reverse order after they are popped out from queue.*/ Stack<Node> myStack = new Stack<>(); Node temp = null; // sz is used for storing // the count of nodes in a level int sz; // Used for changing the direction // of level order traversal int ct = 0; // Used for changing the direction // of level order traversal boolean rightToLeft = false; // Push root node to the queue myQueue.add(node); // Run this while loop till queue got empty while (!myQueue.isEmpty()) { ct++; sz = myQueue.size(); // Do a normal level order traversal for (int i = 0; i < sz; i++) { temp = myQueue.peek(); myQueue.remove(); /*For printing nodes from left to right, simply print the nodes in the order in which they are being popped out from the queue.*/ if (rightToLeft == false) System.out.print(temp.data + " "); /* For printing nodes from right to left, push the nodes to stack instead of printing them.*/ else myStack.push(temp); if (temp.left != null) myQueue.add(temp.left); if (temp.right != null) myQueue.add(temp.right); } if (rightToLeft == true) { // for printing the nodes in order // from right to left while (!myStack.isEmpty()) { temp = myStack.peek(); myStack.pop(); System.out.print(temp.data + " "); } } /*Change the direction of printing nodes after every two levels.*/ if (ct == 2) { rightToLeft = !rightToLeft; ct = 0; } System.out.print("\n"); } } // Utility function to create a new tree node static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp; } // Driver Code public static void main(String[] args) { // Let us create binary tree Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); root.left.left.left = newNode(8); root.left.left.right = newNode(9); root.left.right.left = newNode(3); root.left.right.right = newNode(1); root.right.left.left = newNode(4); root.right.left.right = newNode(2); root.right.right.left = newNode(7); root.right.right.right = newNode(2); root.left.right.left.left = newNode(16); root.left.right.left.right = newNode(17); root.right.left.right.left = newNode(18); root.right.right.left.right = newNode(19); modifiedLevelOrder(root); } } // This code is contributed by 29AjayKumar |
C#
// C# program to print Zig-Zag traversal // in groups of size 2. using System; using System.Collections.Generic; class GFG { // A Binary Tree Node public class Node { public Node left; public int data; public Node right; }; /* Function to print the level order of given binary tree. Direction of printing level order traversal of binary tree changes after every two levels */static void modifiedLevelOrder(Node node) { // For null root if (node == null) return; if (node.left == null && node.right == null) { Console.Write(node.data); return; } // Maintain a queue for // normal level order traversal Queue<Node> myQueue = new Queue<Node>(); /* Maintain a stack for printing nodes in reverse order after they are popped out from queue.*/ Stack<Node> myStack = new Stack<Node>(); Node temp = null; // sz is used for storing // the count of nodes in a level int sz; // Used for changing the direction // of level order traversal int ct = 0; // Used for changing the direction // of level order traversal bool rightToLeft = false; // Push root node to the queue myQueue.Enqueue(node); // Run this while loop // till queue got empty while (myQueue.Count != 0) { ct++; sz = myQueue.Count; // Do a normal level order traversal for (int i = 0; i < sz; i++) { temp = myQueue.Peek(); myQueue.Dequeue(); /* For printing nodes from left to right, simply print the nodes in the order in which they are being popped out from the queue.*/ if (rightToLeft == false) Console.Write(temp.data + " "); /* For printing nodes from right to left, push the nodes to stack instead of printing them.*/ else myStack.Push(temp); if (temp.left != null) myQueue.Enqueue(temp.left); if (temp.right != null) myQueue.Enqueue(temp.right); } if (rightToLeft == true) { // for printing the nodes in order // from right to left while (myStack.Count != 0) { temp = myStack.Peek(); myStack.Pop(); Console.Write(temp.data + " "); } } /*Change the direction of printing nodes after every two levels.*/ if (ct == 2) { rightToLeft = !rightToLeft; ct = 0; } Console.Write("\n"); } } // Utility function to create a new tree node static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp; } // Driver Code public static void Main(String[] args) { // Let us create binary tree Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); root.left.left.left = newNode(8); root.left.left.right = newNode(9); root.left.right.left = newNode(3); root.left.right.right = newNode(1); root.right.left.left = newNode(4); root.right.left.right = newNode(2); root.right.right.left = newNode(7); root.right.right.right = newNode(2); root.left.right.left.left = newNode(16); root.left.right.left.right = newNode(17); root.right.left.right.left = newNode(18); root.right.right.left.right = newNode(19); modifiedLevelOrder(root); } } // This code is contributed by Rajput-Ji |
1 2 3 7 6 5 4 2 7 2 4 1 3 9 8 16 17 18 19
Time Complexity: Each node is traversed at most twice while doing level order traversal, so time complexity would be O(n).
Approach 2:
We make use of queue and stack here, but in a different way. Using macros #define ChangeDirection(Dir) ((Dir) = 1 – (Dir)). In following implementation directs the order of push operations in both queue or stack.
In this way, we will achieve desired modified level order traversal by making use of queue and stack.
// CPP program to print Zig-Zag traversal // in groups of size 2. #include <iostream> #include <stack> #include <queue> using namespace std; #define LEFT 0 #define RIGHT 1 #define ChangeDirection(Dir) ((Dir) = 1 - (Dir)) // A Binary Tree Node struct node { int data; struct node *left, *right; }; // Utility function to create a new tree node node* newNode(int data) { node* temp = new node; temp->data = data; temp->left = temp->right = NULL; return temp; } /* Function to print the level order of given binary tree. Direction of printing level order traversal of binary tree changes after every two levels */void modifiedLevelOrder(struct node *root) { if (!root) return ; int dir = LEFT; struct node *temp; queue <struct node *> Q; stack <struct node *> S; S.push(root); // Run this while loop till queue got empty while (!Q.empty() || !S.empty()) { while (!S.empty()) { temp = S.top(); S.pop(); cout << temp->data << " "; if (dir == LEFT) { if (temp->left) Q.push(temp->left); if (temp->right) Q.push(temp->right); } /* For printing nodes from right to left, push the nodes to stack instead of printing them.*/ else { if (temp->right) Q.push(temp->right); if (temp->left) Q.push(temp->left); } } cout << endl; // for printing the nodes in order // from right to left while (!Q.empty()) { temp = Q.front(); Q.pop(); cout << temp->data << " "; if (dir == LEFT) { if (temp->left) S.push(temp->left); if (temp->right) S.push(temp->right); } else { if (temp->right) S.push(temp->right); if (temp->left) S.push(temp->left); } } cout << endl; // Change the direction of traversal. ChangeDirection(dir); } } // Driver program to test above functions int main() { // Let us create binary tree node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(3); root->left->right->right = newNode(1); root->right->left->left = newNode(4); root->right->left->right = newNode(2); root->right->right->left = newNode(7); root->right->right->right = newNode(2); root->left->right->left->left = newNode(16); root->left->right->left->right = newNode(17); root->right->left->right->left = newNode(18); root->right->right->left->right = newNode(19); modifiedLevelOrder(root); return 0; } |
1 2 3 7 6 5 4 2 7 2 4 1 3 9 8 16 17 18 19
Time Complexity: every node is also traversed twice. There time complexity is still O(n).
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
- Connect Nodes at same Level (Level Order Traversal)
- Level order traversal of Binary Tree using Morris Traversal
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Flatten Binary Tree in order of Level Order Traversal
- Insertion in n-ary tree in given order and Level order traversal
- Print odd positioned nodes of odd levels in level order of the given binary tree
- Print even positioned nodes of even levels in level order of the given binary tree
- Print even positioned nodes of odd levels in level order of the given binary tree
- Print odd positioned nodes of even levels in level order of the given binary tree
- Level order traversal line by line | Set 2 (Using Two Queues)
- Check if two trees are mirror of each other using level order traversal
- Level Order Tree Traversal
- Level order traversal in spiral form
- Reverse Level Order Traversal
- Perfect Binary Tree Specific Level Order Traversal
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Print level order traversal line by line | Set 1
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- General Tree (Each node can have arbitrary number of children) Level Order Traversal
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

