Level order traversal in spiral form | Using one stack and one queue
Last Updated :
26 Aug, 2022
Write a function to print spiral order traversal of a tree. For below tree, function should print 1, 2, 3, 4, 5, 6, 7.

You are allowed to use only one stack.
We have seen recursive and iterative solutions using two stacks . In this post, a solution with one stack and one queue is discussed. The idea is to keep on entering nodes like normal level order traversal, but during printing, in alternative turns push them onto the stack and print them, and in other traversals, just print them the way they are present in the queue.
Following is the implementation of the idea.
C++
// CPP program to print level order traversal
// in spiral form using one queue and one stack.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
/* Utility function to create a new tree node */
Node* newNode(int val)
{
Node* new_node = new Node;
new_node->data = val;
new_node->left = new_node->right = NULL;
return new_node;
}
/* Function to print a tree in spiral form
using one stack */
void printSpiralUsingOneStack(Node* root)
{
if (root == NULL)
return;
stack<int> s;
queue<Node*> q;
bool reverse = true;
q.push(root);
while (!q.empty()) {
int size = q.size();
while (size) {
Node* p = q.front();
q.pop();
// if reverse is true, push node's
// data onto the stack, else print it
if (reverse)
s.push(p->data);
else
cout << p->data << " ";
if (p->left)
q.push(p->left);
if (p->right)
q.push(p->right);
size--;
}
// print nodes from the stack if
// reverse is true
if (reverse) {
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
}
// the next row has to be printed as
// it is, hence change the value of
// reverse
reverse = !reverse;
}
}
// Driver Code
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(7);
root->left->right = newNode(6);
root->right->left = newNode(5);
root->right->right = newNode(4);
printSpiralUsingOneStack(root);
return 0;
}
Java
// Java program to print level order traversal
// in spiral form using one queue and one stack.
import java.util.*;
class GFG
{
static class Node
{
int data;
Node left, right;
};
/* Utility function to create a new tree node */
static Node newNode(int val)
{
Node new_node = new Node();
new_node.data = val;
new_node.left = new_node.right = null;
return new_node;
}
/* Function to print a tree in spiral form
using one stack */
static void printSpiralUsingOneStack(Node root)
{
if (root == null)
return;
Stack<Integer> s = new Stack<Integer>();
Queue<Node> q = new LinkedList<Node>();
boolean reverse = true;
q.add(root);
while (!q.isEmpty())
{
int size = q.size();
while (size > 0)
{
Node p = q.peek();
q.remove();
// if reverse is true, push node's
// data onto the stack, else print it
if (reverse)
s.add(p.data);
else
System.out.print(p.data + " ");
if (p.left != null)
q.add(p.left);
if (p.right != null)
q.add(p.right);
size--;
}
// print nodes from the stack if
// reverse is true
if (reverse)
{
while (!s.empty())
{
System.out.print(s.peek() + " ");
s.pop();
}
}
// the next row has to be printed as
// it is, hence change the value of
// reverse
reverse = !reverse;
}
}
// Driver Code
public static void main(String[] args)
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(7);
root.left.right = newNode(6);
root.right.left = newNode(5);
root.right.right = newNode(4);
printSpiralUsingOneStack(root);
}
}
// This code is contributed by Princi Singh
Python3
# Python program to print level order traversal
# in spiral form using one queue and one stack.
# Utility class to create a new node
class Node:
def __init__(self, key):
self.key = key
self.left = self.right = None
# Utility function to create a new tree node
def newNode(val):
new_node = Node(0)
new_node.data = val
new_node.left = new_node.right = None
return new_node
# Function to print a tree in spiral form
# using one stack
def printSpiralUsingOneStack(root):
if (root == None):
return
s = []
q = []
reverse = True
q.append(root)
while (len(q) > 0) :
size = len(q)
while (size > 0) :
p = q[0]
q.pop(0)
# if reverse is true, push node's
# data onto the stack, else print it
if (reverse):
s.append(p.data)
else:
print( p.data ,end = " ")
if (p.left != None):
q.append(p.left)
if (p.right != None):
q.append(p.right)
size = size - 1
# print nodes from the stack if
# reverse is true
if (reverse) :
while (len(s)) :
print( s[-1],end= " ")
s.pop()
# the next row has to be printed as
# it is, hence change the value of
# reverse
reverse = not reverse
# Driver Code
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(7)
root.left.right = newNode(6)
root.right.left = newNode(5)
root.right.right = newNode(4)
printSpiralUsingOneStack(root)
# This code is contributed by Arnab Kundu
C#
// C# program to print level order traversal
// in spiral form using one queue and one stack.
using System;
using System.Collections.Generic;
class GFG
{
public class Node
{
public int data;
public Node left, right;
};
/* Utility function to create a new tree node */
static Node newNode(int val)
{
Node new_node = new Node();
new_node.data = val;
new_node.left = new_node.right = null;
return new_node;
}
/* Function to print a tree in spiral form
using one stack */
static void printSpiralUsingOneStack(Node root)
{
if (root == null)
return;
Stack<int> s = new Stack<int>();
Queue<Node> q = new Queue<Node>();
Boolean reverse = true;
q.Enqueue(root);
while (q.Count != 0)
{
int size = q.Count;
while (size > 0)
{
Node p = q.Peek();
q.Dequeue();
// if reverse is true, push node's
// data onto the stack, else print it
if (reverse)
s.Push(p.data);
else
Console.Write(p.data + " ");
if (p.left != null)
q.Enqueue(p.left);
if (p.right != null)
q.Enqueue(p.right);
size--;
}
// print nodes from the stack if
// reverse is true
if (reverse)
{
while (s.Count != 0)
{
Console.Write(s.Peek() + " ");
s.Pop();
}
}
// the next row has to be printed as
// it is, hence change the value of
// reverse
reverse = !reverse;
}
}
// Driver Code
public static void Main(String[] args)
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(7);
root.left.right = newNode(6);
root.right.left = newNode(5);
root.right.right = newNode(4);
printSpiralUsingOneStack(root);
}
}
// This code is contributed by Rajput-Jiv
JavaScript
<script>
// Javascript program to print level
// order traversal in spiral form
// using one queue and one stack.
class Node
{
constructor()
{
this.data = 0;
this.left = null;
this.right = null;
}
};
// Utility function to create
// a new tree node
function newNode(val)
{
var new_node = new Node();
new_node.data = val;
new_node.left = new_node.right = null;
return new_node;
}
// Function to print a tree in spiral form
// using one stack
function printSpiralUsingOneStack(root)
{
if (root == null)
return;
var s = [];
var q = [];
var reverse = true;
q.push(root);
while (q.length != 0)
{
var size = q.length;
while (size > 0)
{
var p = q[0];
q.shift();
// If reverse is true, push node's
// data onto the stack, else print it
if (reverse)
s.push(p.data);
else
document.write(p.data + " ");
if (p.left != null)
q.push(p.left);
if (p.right != null)
q.push(p.right);
size--;
}
// Print nodes from the stack if
// reverse is true
if (reverse)
{
while (s.length != 0)
{
document.write(s[s.length - 1] + " ");
s.pop();
}
}
// The next row has to be printed as
// it is, hence change the value of
// reverse
reverse = !reverse;
}
}
// Driver Code
var root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(7);
root.left.right = newNode(6);
root.right.left = newNode(5);
root.right.right = newNode(4);
printSpiralUsingOneStack(root);
// This code is contributed by rutvik_56
</script>
Complexity Analysis:
- Time Complexity : O(n)
- Auxiliary Space : O(n)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read