Zig Zag Level order traversal of a tree using single array
Last Updated :
17 Mar, 2023
Write a function to print spiral order traversal of a tree. For below tree, function should print 1, 2, 3, 4, 5, 6, 7.

We have discussed naive approach and two stack based approach in Level Order with recursion and multiple stacks
The idea behind this approach is first we have to take a queue, a direction flag and a separation flag which is NULL
- Insert the root element into the queue and again insert NULL into the queue.
- For every element in the queue insert its child nodes.
- If a NULL is encountered then check the direction to traverse the particular level is left to right or right to left. If it's an even level then traverse from left to right otherwise traverse the tree in right to level order i.e., from the front to the previous front i.e., from the current NULL to the last NULL that has been visited. This continues till the last level then there the loop breaks and we print what is left (that has not printed) by checking the direction to print.
Following is the implementation of the explanation
C++
// C++ program to print level order traversal
// in spiral form using a single dequeue
#include <bits/stdc++.h>
struct Node {
int data;
struct Node *left, *right;
};
// A utility function to create a new node
struct Node* newNode(int data)
{
struct Node* node = new struct Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// function to print the level order traversal
void levelOrder(struct Node* root, int n)
{
// We can just take the size as H+N which
// implies the height of the tree with the
// size of the tree
struct Node* queue[2 * n];
int top = -1;
int front = 1;
queue[++top] = NULL;
queue[++top] = root;
queue[++top] = NULL;
// struct Node* t=root;
int prevFront = 0, count = 1;
while (1) {
struct Node* curr = queue[front];
// A level separator found
if (curr == NULL) {
// If this is the only item in dequeue
if (front == top)
break;
// Else print contents of previous level
// according to count
else {
if (count % 2 == 0) {
for (int i = prevFront + 1; i < front; i++)
printf("%d ", queue[i]->data);
}
else {
for (int i = front - 1; i > prevFront; i--)
printf("%d ", queue[i]->data);
}
prevFront = front;
count++;
front++;
// Insert a new level separator
queue[++top] = NULL;
continue;
}
}
if (curr->left != NULL)
queue[++top] = curr->left;
if (curr->right != NULL)
queue[++top] = curr->right;
front++;
}
if (count % 2 == 0) {
for (int i = prevFront + 1; i < top; i++)
printf("%d ", queue[i]->data);
}
else {
for (int i = top - 1; i > prevFront; i--)
printf("%d ", queue[i]->data);
}
}
// Driver code
int main()
{
struct 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);
levelOrder(root, 7);
return 0;
}
Java
// Java program to print level order traversal
// in spiral form using a single dequeue
class Solution
{
static class Node
{
int data;
Node left, right;
};
// A utility function to create a new node
static Node newNode(int data)
{
Node node = new Node();
node.data = data;
node.left = node.right = null;
return (node);
}
// function to print the level order traversal
static void levelOrder( Node root, int n)
{
// We can just take the size as H+N which
// implies the height of the tree with the
// size of the tree
Node queue[] = new Node[2 * n];
for(int i = 0; i < 2 * n; i++)
queue[i] = new Node();
int top = -1;
int front = 1;
queue[++top] = null;
queue[++top] = root;
queue[++top] = null;
// Node t=root;
int prevFront = 0, count = 1;
while (true)
{
Node curr = queue[front];
// A level separator found
if (curr == null)
{
// If this is the only item in dequeue
if (front == top)
break;
// Else print contents of previous level
// according to count
else
{
if (count % 2 == 0)
{
for (int i = prevFront + 1; i < front; i++)
System.out.printf("%d ", queue[i].data);
}
else
{
for (int i = front - 1; i > prevFront; i--)
System.out.printf("%d ", queue[i].data);
}
prevFront = front;
count++;
front++;
// Insert a new level separator
queue[++top] = null;
continue;
}
}
if (curr.left != null)
queue[++top] = curr.left;
if (curr.right != null)
queue[++top] = curr.right;
front++;
}
if (count % 2 == 0)
{
for (int i = prevFront + 1; i < top; i++)
System.out.printf("%d ", queue[i].data);
}
else
{
for (int i = top - 1; i > prevFront; i--)
System.out.printf("%d ", queue[i].data);
}
}
// 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);
levelOrder(root, 7);
}
}
// This code is contributed by Arnab Kundu
Python3
# Python program for the above approach
from collections import deque
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def levelOrder(root, n):
queue = deque([None, root, None] + [None]*(2*n - 2))
top = 2
front = 1
prevFront = 0
count = 1
while True:
curr = queue[front]
if curr == None:
if front == top:
break
else:
if count % 2 == 0:
for i in range(prevFront + 1, front):
print(queue[i].data, end=' ')
else:
for i in range(front - 1, prevFront, -1):
print(queue[i].data, end=' ')
prevFront = front
count += 1
front += 1
queue[top+1] = None
top += 1
continue
if curr.left != None:
queue[top+1] = curr.left
top += 1
if curr.right != None:
queue[top+1] = curr.right
top += 1
front += 1
if count % 2 == 0:
for i in range(prevFront + 1, top):
print(queue[i].data, end=' ')
else:
for i in range(top - 1, prevFront, -1):
print(queue[i].data, end=' ')
# Driver code
if __name__ == '__main__':
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(7)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(4)
levelOrder(root, 7)
# This code is contributed by codebraxnzt
JavaScript
<script>
// Javascript program to print level order
// traversal in spiral form using a single dequeue
class Node
{
constructor()
{
this.data = 0;
this.left = null;
this.right = null;
}
};
// A utility function to create a new node
function newNode(data)
{
var node = new Node();
node.data = data;
node.left = node.right = null;
return (node);
}
// Function to print the level order traversal
function levelOrder(root, n)
{
// We can just take the size as H+N which
// implies the height of the tree with the
// size of the tree
var queue = Array(2 * n);
for(var i = 0; i < 2 * n; i++)
queue[i] = new Node();
var top = -1;
var front = 1;
queue[++top] = null;
queue[++top] = root;
queue[++top] = null;
// Node t=root;
var prevFront = 0, count = 1;
while (true)
{
var curr = queue[front];
// A level separator found
if (curr == null)
{
// If this is the only item in dequeue
if (front == top)
break;
// Else print contents of previous level
// according to count
else
{
if (count % 2 == 0)
{
for(var i = prevFront + 1;
i < front; i++)
document.write(" " + queue[i].data);
}
else
{
for(var i = front - 1;
i > prevFront; i--)
document.write(" " + queue[i].data);
}
prevFront = front;
count++;
front++;
// Insert a new level separator
queue[++top] = null;
continue;
}
}
if (curr.left != null)
queue[++top] = curr.left;
if (curr.right != null)
queue[++top] = curr.right;
front++;
}
if (count % 2 == 0)
{
for(var i = prevFront + 1; i < top; i++)
document.write(" " + queue[i].data);
}
else
{
for(var i = top - 1; i > prevFront; i--)
document.write(" " + queue[i].data);
}
}
// 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);
levelOrder(root, 7);
// This code is contributed by rutvik_56
</script>
C#
// C# program to print level order traversal
// in spiral form using a single dequeue
using System;
class GFG
{
public class Node
{
public int data;
public Node left, right;
};
// A utility function to create a new node
static Node newNode(int data)
{
Node node = new Node();
node.data = data;
node.left = node.right = null;
return (node);
}
// function to print the level order traversal
static void levelOrder( Node root, int n)
{
// We can just take the size as H+N which
// implies the height of the tree with the
// size of the tree
Node []queue = new Node[2 * n];
for(int i = 0; i < 2 * n; i++)
queue[i] = new Node();
int top = -1;
int front = 1;
queue[++top] = null;
queue[++top] = root;
queue[++top] = null;
// Node t=root;
int prevFront = 0, count = 1;
while (true)
{
Node curr = queue[front];
// A level separator found
if (curr == null)
{
// If this is the only item in dequeue
if (front == top)
break;
// Else print contents of previous level
// according to count
else
{
if (count % 2 == 0)
{
for (int i = prevFront + 1;
i < front; i++)
Console.Write(" " + queue[i].data);
}
else
{
for (int i = front - 1;
i > prevFront; i--)
Console.Write(" " + queue[i].data);
}
prevFront = front;
count++;
front++;
// Insert a new level separator
queue[++top] = null;
continue;
}
}
if (curr.left != null)
queue[++top] = curr.left;
if (curr.right != null)
queue[++top] = curr.right;
front++;
}
if (count % 2 == 0)
{
for (int i = prevFront + 1; i < top; i++)
Console.Write(" " + queue[i].data);
}
else
{
for (int i = top - 1; i > prevFront; i--)
Console.Write(" " + queue[i].data);
}
}
// 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);
levelOrder(root, 7);
}
}
// This code is contributed by gauravrajput1
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space : O(2*n) = O(n)
Similar Reads
Zig-Zag traversal of a Binary Tree using Recursion Given a binary tree, the task is to find the zigzag level order traversal of the tree. In zig zag traversal starting from the first level go from left to right for odd-numbered levels and right to left for even-numbered levels. Approach:The zigzag traversal of a binary tree involves traversing the t
11 min read
Flatten Binary Tree in order of Zig Zag traversal Given a Binary Tree, the task is to flatten it in order of ZigZag traversal of the tree. In the flattened binary tree, the left node of all the nodes must be NULL.Examples: Input: 1 / \ 5 2 / \ / \ 6 4 9 3 Output: 1 2 5 6 4 9 3 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5 Approach: We will solve this
7 min read
Level order traversal in spiral form | Using Deque 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 th
6 min read
Level Order Traversal in C The Level Order Traversal is a traversal technique used to traverse a tree level by level from top to bottom and from left to right at each level of a tree. In this article, we will learn how to implement level order traversal of a binary tree in C using two different methods. Level order traversal
6 min read
Print all root to leaf paths of an N-ary tree Given an N-Ary tree, the task is to print all root to leaf paths of the given N-ary Tree. Examples: Input: 1 / \ 2 3 / / \ 4 5 6 / \ 7 8 Output:1 2 41 3 51 3 6 71 3 6 8 Input: 1 / | \ 2 5 3 / \ \ 4 5 6Output:1 2 41 2 51 51 3 6 Approach: The idea to solve this problem is to start traversing the N-ary
7 min read
How to Print Data in Binary Tree Level by Level in C++? A binary tree is a non-linear hierarchical data structure where each node can have at most two children which are termed as left and right child. In this article, we will learn how to print data in a binary tree level by level in C++. Example Input: 10 / \ 20 30 / \ / \40 50 60 70Output:10 20 30 40
4 min read
Print N-ary tree graphically Given an N-ary tree, the task is to print the N-ary tree graphically.Graphical Representation of Tree: A representation of tree in which the root is printed in a line and the children nodes are printed in subsequent lines with some amount of indentation. Examples: Input: 0 / | \ / | \ 1 2 3 / \ / |
11 min read
Implementing a BST where every node stores the maximum number of nodes in the path till any leaf Given an array of values. The task is to implement a Binary Search Tree using values of the array where every node stores the maximum number of nodes in the path starting from the node itself and ending at any leaf of the tree. Note: The maximum number of nodes in the path from any node to any leaf
15 min read
ZigZag Level Order Traversal of an N-ary Tree Given a Generic Tree consisting of n nodes, the task is to find the ZigZag Level Order Traversal of the given tree.Note: A generic tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), a generic tree allow
8 min read
Zig-Zag level order traversal of Binary Tree after every K levels Given a binary tree and an integer k, the task is to print the level order traversal in such a way that first k levels are printed from left to right, next k levels are printed from right to left, then next k levels are from left to right and so on.Examples:Input: k = 1 Output:1 3 24 5 6Explanation:
10 min read