VOOZH about

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

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


  • Courses
  • Tutorials
  • Interview Prep

Level order traversal with direction change after every two levels | Recursive Approach

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

Approach:

The idea is to use a recursivemethod to print the elements in every level. Traverse every level in the tree, for every level, check the direction. Use a flag to know the direction of traversal in the tree. If the flag is set to true, print the nodes from right to left in the particular level. If the flag is set to false, print the nodes in that level from left to right. Initially, the flag is set to False, after every 2 levels, flag changes its value to true and vice versa. 

Below is the implementation of the above approach.


Output
1 
2 3 
6 5 4 
1 3 9 8 

Time Complexity: O(n), where n is the number of nodes in the tree (because level order traversal is done and each element is traversed maximum twice
Auxiliary Space: O(h), due to recursion call stack.

Related article:

Comment
Article Tags: