VOOZH about

URL: https://www.geeksforgeeks.org/dsa/level-order-traversal-in-spiral-form/

⇱ Level order traversal in spiral form - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Level order traversal in spiral form

Last Updated : 9 Apr, 2026

Given a binary tree and we have to find the spiral order traversal of the tree and return the list containing the elements.
Spiral order Traversal: Starting from level 0 for root node, for all the even levels we print the node's value from right to left and for all the odd levels we print the node's value from left to right.

Example:

Input: root = [1, 2, 3, 7, 6, 5, 4]

👁 Image

Output: [1, 2, 3, 4, 5, 6, 7]
Explanation: Start with root (1), print level 0 (right to left), level 1 (left to right), and continue alternating.

Input: root = [1, 3, 2]

👁 example-2

Output: [1, 3, 2]
Explanation: Start with root (1), print level 0 (right to left), then level 1 (left to right)

Input: root = [10, 20, 30, 40, 60]

👁 Example-3

Output: [10, 20, 30, 60, 40]
Explanation: Start with root (10), print level 0 (right to left), level 1 (left to right), and continue alternating.

Using Recursion - O(n) Time and O(h) Space

The idea is to first calculate the height of the tree, then recursively traverse each level and print the level order traversal according to the current level being odd or even.

Steps to solve the problem:

  • Find the height h of the binary tree.
  • Use a boolean flag variable ltr (left-to-right), start as false.
  • For each level ,Call printGivenLevel(root, level, ltr).
  • Toggle ltr after each level.
  • If node is null → return.
  • If level == 1 → process the current node.
  • If level > 1,If ltr → recurse left → right otherwise → recurse right → left.

Output
1 2 3 4 5 6 7 

Using Two Stacks - O(n) Time and O(n) Space

The idea is to use two stacks. One stack s1 is used to traverse the current level and the other stack s2 is used to store the nodes of next level.

Steps to solve the problem:

  • Initialize two stacks s1 and s2, push root into s1.
  • While either stack is not empty:
  • From s1: pop nodes, add to result, push right → left children into s2.
  • From s2: pop nodes, add to result, push left → right children into s1.
  • Directions alternate naturally: s1 handles right-to-left, s2 handles left-to-right.

Output
1 2 3 4 5 6 7 

Using Deque - O(n) Time and O(n) Space

The idea is to use Doubly Ended Queues, then push and pop the nodes from each end in alternate order.

Steps to solve the problem:

  • Start with a deque containing the root and a flag variable reverse = true.
  • While deque is not empty:
  • Process all nodes of the current level.
  • If reverse → pop from back, add children (right → left) at front.
  • Else → pop from front, add children (left → right) at back.
  • Flip reverse for each level.

Output
1 2 3 4 5 6 7 
Comment