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:

C++
// C++ implementation to find Level order traversal
// with direction change every 2 Levels using 
// Stack + Queue
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Function to perform modified level-order traversal
vector<vector<int>> modifiedLevelOrderTraversal(Node* root) {
    vector<vector<int>> result;
    
    if (!root) return result;

    // Queue to store the nodes
    queue<Node*> q;
    q.push(root);

    bool leftToRight = true;
    int levelCounter = 0;

    while (!q.empty()) {
        int size = q.size();
        vector<int> level;

        // Stack to reverse the level if needed
        stack<int> s;

        for (int i = 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 stack
        if (!leftToRight) {
            while (!s.empty()) {
                level.push_back(s.top());
                s.pop();
            }
        }

        result.push_back(level);
        levelCounter++;

        // Toggle direction after every two levels
        if (levelCounter % 2 == 0) {
            leftToRight = !leftToRight;
        }
    }

    return result;
}

void print2DArray(vector<vector<int>> arr) {
    for (auto row : arr) {
        for (int val : row) {
            cout << val << " ";
        }
        cout << endl;
    }
}

int main() {

    // Binary tree structure:
    //
    //        1
    //       / \
    //      2   3
    //     / \   \
    //    4   5   6

    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->right->right = new Node(6);
    vector<vector<int>> result 
               = modifiedLevelOrderTraversal(root);

    print2DArray(result);

    return 0;
}
Java
// Java implementation to find Level order traversal
// with direction change every 2 Levels using 
// Stack + Queue
import java.util.*;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

// Function to perform modified level-order traversal
class GfG {
    
    static List<List<Integer>> 
                 modifiedLevelOrderTraversal(Node root) {
      
        List<List<Integer>> result = new ArrayList<>();
        
        if (root == null) return result;

        // Queue to store the nodes
        Queue<Node> q = new LinkedList<>();
        q.add(root);

        boolean leftToRight = true;
        int levelCounter = 0;

        while (!q.isEmpty()) {
          
            int size = q.size();
            List<Integer> level = new ArrayList<>();
            Stack<Integer> s = new Stack<>();

            for (int i = 0; i < size; i++) {
                Node curr = 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 levels
            if (levelCounter % 2 == 0) {
                leftToRight = !leftToRight;
            }
        }

        return result;
    }

    static void print2DArray(List<List<Integer>> arr) {
        for (List<Integer> row : arr) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {

        // Binary tree structure:
        //
        //        1
        //       / \
        //      2   3
        //     / \   \
        //    4   5   6
      
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.right = new Node(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 + Queue
from collections import deque

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function to perform modified level-order
# traversal
def modified_level_order_traversal(root):
    result = []
    
    if not root:
        return result

    # Queue to store the nodes
    q = deque([root])

    left_to_right = True
    level_counter = 0

    while q:
        size = len(q)
        level = []
        s = []

        for _ in range(size):
            curr = q.popleft()

            if left_to_right:
                level.append(curr.data)
            else:
                s.append(curr.data)

            if curr.left:
                q.append(curr.left)
            if curr.right:
                q.append(curr.right)

        if not left_to_right:
            while s:
                level.append(s.pop())

        result.append(level)
        level_counter += 1

        # Toggle direction after every two levels
        if level_counter % 2 == 0:
            left_to_right = not left_to_right

    return result

def print_2d_array(arr):
    for row in arr:
        print(" ".join(map(str, row)))

if __name__ == "__main__":

    
    # Binary tree structure:
    #
    #        1
    #       / \
    #      2   3
    #     / \   \
    #    4   5   6
    root = 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 + Queue
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
  
    // Function to perform modified level-order traversal
    static List<List<int>>
          ModifiedLevelOrderTraversal(Node root) {
        List<List<int>> result = new List<List<int>>();

        if (root == null) return result;

        // Queue to store the nodes
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);

        bool leftToRight = true;
        int levelCounter = 0;

        while (q.Count > 0) {
            int size = q.Count;
            List<int> level = new List<int>();
            Stack<int> s = new Stack<int>();

            for (int i = 0; i < size; i++) {
                Node curr = 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 levels
            if (levelCounter % 2 == 0) {
                leftToRight = !leftToRight;
            }
        }

        return result;
    }

    static void Print2DArray(List<List<int>> arr) {
        foreach (var row in arr) {
            foreach (var val in row) {
                Console.Write(val + " ");
            }
            Console.WriteLine();
        }
    }

    static void Main(string[] args) {

       // Binary tree structure:
        //
        //        1
        //       / \
        //      2   3
        //     / \   \
        //    4   5   6
      
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.right = new Node(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 + Queue
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function to perform modified level-order traversal
function modifiedLevelOrderTraversal(root) {
    const result = [];
    
    if (!root) return result;

    // Queue to store the nodes
    const q = [];
    q.push(root);

    let leftToRight = true;
    let levelCounter = 0;

    while (q.length > 0) {
        const size = q.length;
        const level = [];
        const s = [];

        for (let i = 0; i < size; i++) {
            const curr = 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 levels
        if (levelCounter % 2 === 0) {
            leftToRight = !leftToRight;
        }
    }

    return result;
}

function print2DArray(arr) {
    for (const row of arr) {
        console.log(row.join(' '));
    }
}

// Binary tree structure:
// 
//        1
//       / \
//      2   3
//     / \   \
//    4   5   6

let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.right = new Node(6);

const result = 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.

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

Comment