Level order traversal in spiral form | Using Deque
Last Updated :
13 May, 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]
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]
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.
C++
// C++ program to print level order traversal
// in spiral form using one deque.
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int val)
{
data = val;
left = NULL;
right = NULL;
}
};
void spiralOrder(Node* root)
{
deque<Node*> d;
// Push root
d.push_back(root);
// Direction 0 shows print right to left
// and for Direction 1 left to right
int dir = 0;
while (!d.empty()) {
int size = d.size();
while (size--) {
// One whole level
// will be print in this loop
if (dir == 0) {
Node* temp = d.back();
d.pop_back();
if (temp->right)
d.push_front(temp->right);
if (temp->left)
d.push_front(temp->left);
cout << temp->data << " ";
}
else {
Node* temp = d.front();
d.pop_front();
if (temp->left)
d.push_back(temp->left);
if (temp->right)
d.push_back(temp->right);
cout << temp->data << " ";
}
}
cout << endl;
// Direction change
dir = 1 - dir;
}
}
int main()
{
// Build the Tree
Node* root = new Node(10);
root->left = new Node(20);
root->right = new Node(30);
root->left->left = new Node(40);
root->left->right = new Node(60);
// Call the Function
spiralOrder(root);
return 0;
}
Java
// Java program to print level order traversal
// in spiral form using one deque.
import java.util.*;
class GFG
{
static class Node
{
int data;
Node left, right;
Node(int val)
{
data = val;
left = null;
right = null;
}
};
static void spiralOrder(Node root)
{
Deque<Node> d = new LinkedList<Node>();
// Push root
d.addLast(root);
// Direction 0 shows print right to left
// and for Direction 1 left to right
int dir = 0;
while (d.size() > 0)
{
int size = d.size();
while (size-->0)
{
// One whole level
// will be print in this loop
if (dir == 0)
{
Node temp = d.peekLast();
d.pollLast();
if (temp.right != null)
d.addFirst(temp.right);
if (temp.left != null)
d.addFirst(temp.left);
System.out.print(temp.data + " ");
}
else
{
Node temp = d.peekFirst();
d.pollFirst();
if (temp.left != null)
d.addLast(temp.left);
if (temp.right != null)
d.addLast(temp.right);
System.out.print(temp.data + " ");
}
}
System.out.println();
// Direction change
dir = 1 - dir;
}
}
// Driver code
public static void main(String args[])
{
// Build the Tree
Node root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(60);
// Call the Function
spiralOrder(root);
}
}
// This code is contributed by Arnab Kundu
Python3
# Python program to print level order traversal
# in spiral form using one deque.
class Node :
def __init__(self,val) :
self.data = val;
self.left = None;
self.right = None;
def spiralOrder(root) :
d = [];
# Push root
d.append(root);
# Direction 0 shows print right to left
# and for Direction 1 left to right
direct = 0;
while (len(d) != 0) :
size = len(d);
while (size) :
size -= 1;
# One whole level
# will be print in this loop
if (direct == 0) :
temp = d.pop();
if (temp.right) :
d.insert(0, temp.right);
if (temp.left) :
d.insert(0, temp.left);
print(temp.data, end= " ");
else :
temp = d[0];
d.pop(0);
if (temp.left) :
d.append(temp.left);
if (temp.right) :
d.append(temp.right);
print(temp.data ,end= " ");
print()
# Direction change
direct = 1 - direct;
if __name__ == "__main__" :
# Build the Tree
root = Node(10);
root.left = Node(20);
root.right = Node(30);
root.left.left = Node(40);
root.left.right = Node(60);
# Call the Function
spiralOrder(root);
# This code is contributed by AnkitRai01
C#
//C# code for the above approach
using System;
using System.Collections.Generic;
class GFG
{
class Node
{
public int data;
public Node left, right;
public Node(int val)
{
data = val;
left = null;
right = null;
}
}
static void SpiralOrder(Node root)
{
Queue<Node> d = new Queue<Node>();
// Push root
d.Enqueue(root);
// Direction 0 shows print right to left
// and for Direction 1 left to right
int dir = 0;
while (d.Count > 0)
{
int size = d.Count;
while (size-- > 0)
{
// One whole level
// will be print in this loop
if (dir == 1)
{
Node temp = d.Peek();
d.Dequeue();
if (temp.right != null)
d.Enqueue(temp.right);
if (temp.left != null)
d.Enqueue(temp.left);
Console.Write(temp.data + " ");
}
else
{
Node temp = d.Peek();
d.Dequeue();
if (temp.left != null)
d.Enqueue(temp.left);
if (temp.right != null)
d.Enqueue(temp.right);
Console.Write(temp.data + " ");
}
}
Console.WriteLine();
// Direction change
dir = 1 - dir;
}
}
// Driver code
// Driver code
static void Main(string[] args)
{
// Build the Tree
Node root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(60);
// Call the Function
SpiralOrder(root);
}
}
//This code is contributed by Potta Lokesh
JavaScript
<script>
// JavaScript program to print level order traversal
// in spiral form using one deque.
class Node {
constructor(val)
{
this.data = val;
this.left = null;
this.right = null;
}
};
function spiralOrder(root)
{
var d = [];
// Push root
d.push(root);
// Direction 0 shows print right to left
// and for Direction 1 left to right
var dir = 0;
while (d.length!=0) {
var size = d.length;
while (size-- >0) {
// One whole level
// will be print in this loop
if (dir == 0) {
var temp = d[d.length-1];
d.pop();
if (temp.right!= null)
d.unshift(temp.right);
if (temp.left!= null)
d.unshift(temp.left);
document.write( temp.data + " ");
}
else {
var temp = d[0];
d.shift();
if (temp.left != null)
d.push(temp.left);
if (temp.right!= null)
d.push(temp.right);
document.write( temp.data + " ");
}
}
document.write("<br>");
// Direction change
dir = 1 - dir;
}
}
// Build the Tree
var root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(60);
// Call the Function
spiralOrder(root);
</script>
Time Complexity: O(N), where N is the number of Nodes
Space Complexity: O(N), where N is the number of Nodes
Similar Reads
Level order traversal in spiral form 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:Â 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 nod
15+ min read
Level order traversal in spiral form using stack and multimap Given a binary tree of N nodes, the task is to print level order traversal in a spiral form. In spiral form, nodes at the first and second level of tree are printed normally (left to right), after which nodes at alternate levels are printed in reverse order. Examples: Input: N = 3 1 / \ 3 2 Output:
6 min read
Level order traversal of Binary Tree using Morris Traversal Given a binary tree, the task is to traverse the Binary Tree in level order fashion.Examples: Input: 1 / \ 2 3 Output: 1 2 3 Input: 5 / \ 2 3 \ 6 Output: 5 2 3 6 Approach: The idea is to use Morris Preorder Traversal to traverse the tree in level order traversal.Observations: There are mainly two ob
11 min read
Specific Level Order Traversal of Binary Tree Given a Binary Tree, the task is to perform a Specific Level Order Traversal of the tree such that at each level print 1st element then the last element, then 2nd element and 2nd last element, until all elements of that level are printed and so on.Examples:Input: Output: 5 3 7 2 8 4 6 9 0 5 1 Explan
8 min read
Level of Each node in a Tree from source node (using BFS) Given a tree with v vertices, find the level of each node in a tree from the source node. Examples: Input : Output : Node Level 0 0 1 1 2 1 3 2 4 2 5 2 6 2 7 3 Explanation : Input: Output : Node Level 0 0 1 1 2 1 3 2 4 2 Explanation: Approach: BFS(Breadth-First Search) is a graph traversal technique
8 min read
Reverse Level Order Traversal Given a binary tree, the task is to find its reverse level order traversal. The idea is to print the last level first, then the second last level, and so on. Like Level order traversal, every level is printed from left to right.Examples: Input: Output:4 52 31Table of Content[Naive Approach] Using Re
15+ min read