VOOZH about

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

⇱ Level order traversal in spiral form | Using Deque - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Level order traversal in spiral form | Using Deque

Last Updated : 12 Jul, 2025

Given a binary tree and the task is to find the spiral order traversal of the tree and return the list containing the elements.
Spiral order Traversal mean: 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.

Examples:

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.

Approach

We have seen recursive and iterative solutions using two stacks and an approach using one stack and one queue. In this post, a solution with one deque is discussed. The idea is to use a direction variable and decide whether to pop elements from the front or from the rear based on the value of this direction variable.


Output
10 
20 30 
60 40

Time Complexity: O(N), where N is the number of Nodes
Space Complexity: O(N), where N is the number of Nodes

Comment
Article Tags:
Article Tags: