VOOZH about

URL: https://www.geeksforgeeks.org/dsa/level-order-traversal-direction-change-every-two-levels/

⇱ Level order traversal with direction change after every two levels - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:

👁 level-order-traversal-with-direction-change-after-every-two-levels

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.

👁 level-order-traversal-with-direction-change-after-every-two-levels-2

[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:


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.

Please refer to Level order traversal with direction change after every two levels | Recursive Approach for implementation.

Comment
Article Tags:
Article Tags: