Clockwise Spiral Traversal of Binary Tree
Last Updated :
01 Feb, 2023
Given a Binary Tree. The task is to print the circular clockwise spiral order traversal of the given binary tree.

For the above binary tree, the circular clockwise spiral order traversal will be 1, 4, 5, 6, 7, 2, 3.

Examples:
Input :
10
/ \
12 13
/ \
14 15
/ \ / \
21 22 23 24
Output : 10, 24, 23, 22, 21, 12, 13, 15, 14
Approach:
- First, calculate the width of the given tree.
- Create an auxiliary 2D array of order (width*width)
- Do level order traversal of the binary tree and store levels in the newly created 2D matrix one by one in respective rows. That is, store nodes at level 0 at row indexed 0, nodes at level 1 at row indexed 1, and so on.
- Finally, traverse the 2d array in the below fashion:
- Start from the first row from left to right and print elements.
- Then traverse the last row from right to left and print elements.
- Again traverse the second row from left to right and print.
- The second last row from right to left and so on repeats the steps until the complete 2-D array is traversed.
Below is the implementation of the above approach:
C++
// C++ program for Clockwise Spiral Traversal
// of Binary Tree
#include <bits/stdc++.h>
using namespace std;
// A Tree node
struct Node {
int key;
struct Node *left, *right;
};
// Utility function to create a new node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
//function to calculate the height of the tree
int findHeight(struct Node* node)
{
//Base condition
if(node == NULL) return 0;
int leftHeight = findHeight(node->left);
int rightHeight = findHeight(node->right);
//return maximum of left or right subtree height addition with one
return 1+(leftHeight > rightHeight ? leftHeight : rightHeight );
}
// Function to find the width of tree
void findWidth(struct Node* node, int& maxValue,
int& minValue, int hd)
{
if (node == NULL)
return;
if (hd > maxValue) {
maxValue = hd;
}
if (hd < minValue) {
minValue = hd;
}
findWidth(node->left, maxValue, minValue, hd - 1);
findWidth(node->right, maxValue, minValue, hd + 1);
}
// Function to traverse the tree and
// store level order traversal in a matrix
void BFS(int** mtrx, struct Node* node)
{
// Create queue for storing
// the addresses of nodes
queue<struct Node*> qu;
qu.push(node);
int i = -1, j = -1;
struct Node* poped_node = NULL;
while (!qu.empty()) {
i++;
int qsize = qu.size();
while (qsize--) {
j++;
poped_node = qu.front();
// Store data of node into the matrix
mtrx[i][j] = poped_node->key;
qu.pop();
if (poped_node->left != NULL) {
qu.push(poped_node->left);
}
if (poped_node->right != NULL) {
qu.push(poped_node->right);
}
}
j = -1;
}
}
// Function for Clockwise Spiral Traversal
// of Binary Tree
void traverse_matrix(int** mtrx, int height, int width)
{
int j = 0, k1 = 0, k2 = 0, k3 = height - 1;
int k4 = width - 1;
for (int round = 0; round < height / 2; round++) {
for (j = k2; j < width; j++) {
// only print those values which
// are not MAX_INTEGER
if (mtrx[k1][j] != INT_MAX) {
cout << mtrx[k1][j] << ", ";
}
}
k2 = 0;
k1++;
for (j = k4; j >= 0; j--) {
// only print those values which are
// not MAX_INTEGER
if (mtrx[k3][j] != INT_MAX) {
cout << mtrx[k3][j] << ", ";
}
}
k4 = width - 1;
k3--;
}
// condition (one row may be left traversing)
// if number of rows in matrix are odd
if (height % 2 != 0) {
for (j = k2; j < width; j++) {
// only print those values which are
// not MAX_INTEGER
if (mtrx[k1][j] != INT_MAX) {
cout << mtrx[k1][j] << ", ";
}
}
}
}
// A utility function to print clockwise
// spiral traversal of tree
void printPattern(struct Node* node)
{
// max, min has taken for
// calculating width of tree
int max_value = INT_MIN;
int min_value = INT_MAX;
int hd = 0;
// calculate the width of a tree
findWidth(node, max_value, min_value, hd);
int width = max_value + abs(min_value);
//calculate the height of the tree
int height = findHeight(node);
// use double pointer to create 2D array
int** mtrx = new int*[height];
// initialize width for each row of matrix
for (int i = 0; i < height; i++) {
mtrx[i] = new int[width];
}
// initialize complete matrix with
// MAX INTEGER(purpose garbage)
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
mtrx[i][j] = INT_MAX;
}
}
// Store the BFS traversal of the tree
// into the 2-D matrix
BFS(mtrx, node);
// Print the circular clockwise spiral
// traversal of the tree
traverse_matrix(mtrx, height, width);
// release extra memory
// allocated for matrix
free(mtrx);
}
// Driver Code
int main()
{
/* 10
/ \
12 13
/ \
14 15
/ \ / \
21 22 23 24
Let us create Binary Tree as shown
in above example */
Node* root = newNode(10);
root->left = newNode(12);
root->right = newNode(13);
root->right->left = newNode(14);
root->right->right = newNode(15);
root->right->left->left = newNode(21);
root->right->left->right = newNode(22);
root->right->right->left = newNode(23);
root->right->right->right = newNode(24);
cout << "Circular Clockwise Spiral Traversal : \n";
printPattern(root);
return 0;
}
// This code is contributed by MOHAMMAD MUDASSIR
Java
// Java program for above approach
import java.util.*;
// A Tree node
class Node {
int key;
Node left, right;
Node(int key)
{
this.key = key;
left = right = null;
}
}
class BinaryTree {
// root of the binary tree
Node root;
// function to calculate the height of the tree
int findHeight(Node node)
{
// Base condition
if (node == null)
return 0;
int leftHeight = findHeight(node.left);
int rightHeight = findHeight(node.right);
// return maximum of left or right subtree height
// addition with one
return 1
+ (leftHeight > rightHeight ? leftHeight
: rightHeight);
}
// Function to find the width of tree
void findWidth(Node node, int[] maxValue,
int[] minValue, int hd)
{
if (node == null)
return;
if (hd > maxValue[0]) {
maxValue[0] = hd;
}
if (hd < minValue[0]) {
minValue[0] = hd;
}
findWidth(node.left, maxValue, minValue, hd - 1);
findWidth(node.right, maxValue, minValue, hd + 1);
}
// Function to traverse the tree and
// store level order traversal in a matrix
void BFS(int[][] mtrx, Node node)
{
// Create queue for storing
// the addresses of nodes
Queue<Node> qu = new LinkedList<Node>();
qu.add(node);
int i = -1, j = -1;
Node poped_node;
while (!qu.isEmpty()) {
i++;
int qsize = qu.size();
while (qsize-- > 0) {
j++;
poped_node = qu.remove();
// Store data of node into the matrix
mtrx[i][j] = poped_node.key;
if (poped_node.left != null) {
qu.add(poped_node.left);
}
if (poped_node.right != null) {
qu.add(poped_node.right);
}
}
j = -1;
}
}
// Function for Clockwise Spiral Traversal
// of Binary Tree
void traverse_matrix(int[][] mtrx, int height,
int width)
{
int j = 0, k1 = 0, k2 = 0, k3 = height - 1;
int k4 = width - 1;
for (int round = 0; round < height / 2; round++) {
for (j = k2; j < width; j++) {
// only print those values which
// are not MAX_INTEGER
if (mtrx[k1][j] != Integer.MAX_VALUE) {
System.out.print(mtrx[k1][j] + ", ");
}
}
k2 = 0;
k1++;
for (j = k4; j >= 0; j--) {
// only print those values which are
// not MAX_INTEGER
if (mtrx[k3][j] != Integer.MAX_VALUE) {
System.out.print(mtrx[k3][j] + ", ");
}
}
k4 = width - 1;
k3--;
}
// condition (one row may be left traversing)
// if number of rows in matrix are odd
if (height % 2 != 0) {
for (j = k2; j < width; j++) {
// only print those values which are
// not MAX_INTEGER
if (mtrx[k1][j] != Integer.MAX_VALUE) {
System.out.print(mtrx[k1][j] + ", ");
}
}
}
}
// A utility function to print clockwise
// spiral traversal of tree
void printPattern(Node node)
{
// max, min has taken for
// calculating width of tree
int[] max_value = new int[1];
max_value[0] = Integer.MIN_VALUE;
int[] min_value = new int[1];
min_value[0] = Integer.MAX_VALUE;
int hd = 0;
// calculate the width of a tree
findWidth(node, max_value, min_value, hd);
int width = max_value[0] + Math.abs(min_value[0]);
// calculate the height of the tree
int height = findHeight(node);
// use double pointer to create 2D array
int[][] mtrx = new int[height][width];
// initialize complete matrix with
// MAX INTEGER(purpose garbage)
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
mtrx[i][j] = Integer.MAX_VALUE;
}
}
// Store the BFS traversal of the tree
// into the 2-D matrix
BFS(mtrx, node);
// Print the circular clockwise spiral
// traversal of the tree
traverse_matrix(mtrx, height, width);
}
// Driver Code
public static void main(String[] args)
{
/* 10
/ \
12 13
/ \
14 15
/ \ / \
21 22 23 24
Let us create Binary Tree as shown
in above example */
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(12);
tree.root.right = new Node(13);
tree.root.right.left = new Node(14);
tree.root.right.right = new Node(15);
tree.root.right.left.left = new Node(21);
tree.root.right.left.right = new Node(22);
tree.root.right.right.left = new Node(23);
tree.root.right.right.right = new Node(24);
System.out.println(
"Circular Clockwise Spiral Traversal : ");
tree.printPattern(tree.root);
}
}
// This code is contributed by adityamaharshi21
Python3
# Python3 program for Clockwise Spiral
# Traversal of Binary Tree
INT_MAX = 2**31
INT_MIN = -2**31
# Binary tree node
class newNode:
# Constructor to create a newNode
def __init__(self, data):
self.key = data
self.left = None
self.right = None
# Function to find the width of tree
def findWidth(node, maxValue, minValue, hd):
if (node == None):
return
if (hd > maxValue[0]):
maxValue[0] = hd
if (hd < minValue[0]):
minValue[0] = hd
findWidth(node.left, maxValue,
minValue, hd - 1)
findWidth(node.right, maxValue,
minValue, hd + 1)
# Function to traverse the tree and
# store level order traversal in a matrix
def BFS(mtrx,node):
# Create queue for storing
# the addresses of nodes
qu = []
qu.append(node)
i = -1
j = -1
poped_node = None
while (len(qu)):
i += 1
qsize = len(qu)
while (qsize > 0):
qsize -= 1
j += 1
poped_node = qu[0]
# Store data of node into the matrix
mtrx[i][j] = poped_node.key
qu.pop(0)
if (poped_node.left != None):
qu.append(poped_node.left)
if (poped_node.right != None):
qu.append(poped_node.right)
j = -1
# Function for Clockwise Spiral
# Traversal of Binary Tree
def traverse_matrix(mtrx, width):
j = 0
k1 = 0
k2 = 0
k3 = width - 1
k4 = width - 1
for round in range(width // 2):
for j in range(k2, width):
# only print those values which
# are not MAX_INTEGER
if (mtrx[k1][j] != INT_MAX):
print(mtrx[k1][j], ", ", end = "")
k2 = 0
k1 += 1
for j in range(k4, -1, -1):
# only print those values which are
# not MAX_INTEGER
if (mtrx[k3][j] != INT_MAX):
print(mtrx[k3][j], ", ", end = "")
k4 = width - 1
k3 -= 1
# condition (one row may be left traversing)
# if number of rows in matrix are odd
if (width % 2 != 0):
for j in range(k2, width):
# only print those values which
# are not MAX_INTEGER
if (mtrx[k1][j] != INT_MAX):
print(mtrx[k1][j], ", ", end = "")
# A utility function to prclockwise
# spiral traversal of tree
def printPattern(node):
# max, min has taken for
# calculating width of tree
max_value = [INT_MIN]
min_value = [INT_MAX ]
hd = 0
# calculate the width of a tree
findWidth(node, max_value, min_value, hd)
width = max_value[0] + abs(min_value[0])
# use double pointer to
# create 2D array
mtrx = [0]*width
# initialize width for each
# row of matrix
for i in range(width):
mtrx[i] = [0] * width
# initialize complete matrix with
# MAX INTEGER(purpose garbage)
for i in range(width):
for j in range(width):
mtrx[i][j] = INT_MAX
# Store the BFS traversal of the
# tree into the 2-D matrix
BFS(mtrx, node)
# Print the circular clockwise spiral
# traversal of the tree
traverse_matrix(mtrx, width)
# Driver Code
if __name__ == '__main__':
""" 10
/ \
12 13
/ \
14 15
/ \ / \
21 22 23 24
Let us create Binary Tree as shown
in above example """
root = newNode(10)
root.left = newNode(12)
root.right = newNode(13)
root.right.left = newNode(14)
root.right.right = newNode(15)
root.right.left.left = newNode(21)
root.right.left.right = newNode(22)
root.right.right.left = newNode(23)
root.right.right.right = newNode(24)
print("Circular Clockwise Spiral Traversal :")
printPattern(root)
# This code is contributed by
# SHUBHAMSINGH10
C#
using System;
using System.Collections.Generic;
// A Tree node
class Node {
public int key;
public Node left, right;
public Node(int key)
{
this.key = key;
left = right = null;
}
}
class BinaryTree {
// root of the binary tree
public Node root;
// function to calculate the height of the tree
public int findHeight(Node node)
{
// Base condition
if (node == null)
return 0;
int leftHeight = findHeight(node.left);
int rightHeight = findHeight(node.right);
// return maximum of left or right subtree height
// addition with one
return 1
+ (leftHeight > rightHeight ? leftHeight
: rightHeight);
}
// Function to find the width of tree
public void findWidth(Node node, int[] maxValue,
int[] minValue, int hd)
{
if (node == null)
return;
if (hd > maxValue[0]) {
maxValue[0] = hd;
}
if (hd < minValue[0]) {
minValue[0] = hd;
}
findWidth(node.left, maxValue, minValue, hd - 1);
findWidth(node.right, maxValue, minValue, hd + 1);
}
// Function to traverse the tree and
// store level order traversal in a matrix
public void BFS(int[, ] mtrx, Node node)
{
// Create queue for storing
// the addresses of nodes
Queue<Node> qu = new Queue<Node>();
qu.Enqueue(node);
int i = -1, j = -1;
Node poped_node;
while (qu.Count != 0) {
i++;
int qsize = qu.Count;
while (qsize-- > 0) {
j++;
poped_node = qu.Dequeue();
// Store data of node into the matrix
mtrx[i, j] = poped_node.key;
if (poped_node.left != null) {
qu.Enqueue(poped_node.left);
}
if (poped_node.right != null) {
qu.Enqueue(poped_node.right);
}
}
j = -1;
}
}
// Function for Clockwise Spiral Traversal
// of Binary Tree
public void traverse_matrix(int[, ] mtrx, int height,
int width)
{
int j = 0, k1 = 0, k2 = 0, k3 = height - 1;
int k4 = width - 1;
for (int round = 0; round < height / 2; round++) {
for (j = k2; j < width; j++) {
// only print those values which
// are not MAX_INTEGER
if (mtrx[k1, j] != int.MaxValue) {
Console.Write(mtrx[k1, j] + ", ");
}
}
k2 = 0;
k1++;
for (j = k4; j >= 0; j--) {
// only print those values which are
// not MAX_INTEGER
if (mtrx[k3, j] != int.MaxValue) {
Console.Write(mtrx[k3, j] + ", ");
}
}
k4 = width - 1;
k3--;
}
// condition (one row may be left traversing)
// if number of rows in matrix are odd
if (height % 2 != 0) {
for (j = k2; j < width; j++) {
// only print those values which are
// not MAX_INTEGER
if (mtrx[k1, j] != int.MaxValue) {
Console.Write(mtrx[k1, j] + ", ");
}
}
}
}
// A utility function to print clockwise
public void print_spiral_traversal(Node node)
{
int height = findHeight(node);
int width = (int)Math.Pow(2, height - 1);
int[, ] mtrx = new int[height, width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
mtrx[i, j] = int.MaxValue;
}
}
BFS(mtrx, node);
traverse_matrix(mtrx, height, width);
}
// Driver code
public static void Main(string[] args)
{
BinaryTree tree = new BinaryTree();
// Let us create a binary tree shown
// in above diagram
tree.root = new Node(10);
tree.root.left = new Node(12);
tree.root.right = new Node(13);
tree.root.left.left = new Node(14);
tree.root.left.right = new Node(15);
tree.root.right.left = new Node(21);
tree.root.right.right = new Node(22);
tree.root.right.right.left = new Node(23);
tree.root.right.right.right = new Node(24);
Console.WriteLine(
"Circular Clockwise Spiral Traversal : ");
tree.print_spiral_traversal(tree.root);
}
}
JavaScript
<script>
//JavaScript code for the above approach
let INT_MAX = Math.pow(2, 31);
let INT_MIN = -Math.pow(2, 31);
class Node {
constructor(data) {
this.key = data;
this.left = null;
this.right = null;
}
}
function findWidth(node, maxValue, minValue, hd) {
if (!node) return;
if (hd > maxValue[0]) maxValue[0] = hd;
if (hd < minValue[0]) minValue[0] = hd;
findWidth(node.left, maxValue, minValue, hd - 1);
findWidth(node.right, maxValue, minValue, hd + 1);
}
function BFS(mtrx, node) {
let qu = [];
qu.push(node);
let i = -1;
let j = -1;
let popedNode = null;
while (qu.length) {
i += 1;
let qsize = qu.length;
while (qsize > 0) {
qsize -= 1;
j += 1;
popedNode = qu[0];
mtrx[i][j] = popedNode.key;
qu.shift();
if (popedNode.left) qu.push(popedNode.left);
if (popedNode.right) qu.push(popedNode.right);
}
j = -1;
}
}
function traverseMatrix(mtrx, width) {
let j = 0;
let k1 = 0;
let k2 = 0;
let k3 = width - 1;
let k4 = width - 1;
for (let round = 0; round < width / 2; round++) {
for (j = k2; j < width; j++) {
if (mtrx[k1][j] !== INT_MAX) document.write(mtrx[k1][j] + ", ");
}
k2 = 0;
k1 += 1;
for (j = k4; j >= 0; j--) {
if (mtrx[k3][j] !== INT_MAX) document.write(mtrx[k3][j] + ", ");
}
k4 = width - 1;
k3 -= 1;
}
if (width % 2 !== 0) {
for (j = k2; j < width; j++) {
if (mtrx[k1][j] !== INT_MAX) document.write(mtrx[k1][j] + ", ");
}
}
}
function printPattern(node) {
let maxValue = [INT_MIN];
let minValue = [INT_MAX];
let hd = 0;
findWidth(node, maxValue, minValue, hd);
let width = maxValue[0] + Math.abs(minValue[0]);
let mtrx = new Array(width);
for (let i = 0; i < width; i++) {
mtrx[i] = new Array(width).fill(INT_MAX);
}
BFS(mtrx, node);
traverseMatrix(mtrx, width);
}
let root = new Node(10);
root.left = new Node(12);
root.right = new Node(13);
root.right.left = new Node(14);
root.right.right = new Node(15);
root.right.left.left = new Node(21);
root.right.left.right = new Node(22);
root.right.right.left = new Node(23);
root.right.right.right = new Node(24);
document.write("Circular Clockwise Spiral Traversal :"+"<br>");
printPattern(root);
// This code is contributed by Potta Lokesh
</script>
Output: Circular Clockwise Spiral Traversal :
10, 24, 23, 22, 21, 12, 13, 15, 14,
Time Complexity: O(N), N is the number of nodes.
Auxiliary Space: O(N).
Similar Reads
Clockwise Spiral Traversal of Binary Tree | Set - 2
Given a Binary Tree. The task is to print the circular clockwise spiral order traversal of the given binary tree.Examples: Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output :1 9 8 7 2 3 6 5 4 Input : 20 / \ 8 22 / \ / \ 5 3 4 25 / \ 10 14 Output :20 14 10 8 22 25 4 3 5 We have already discussed Clock
11 min read
Reverse Anti Clockwise Spiral Traversal of a Binary Tree
Given a binary tree, the task is to print the nodes of the tree in a reverse anti-clockwise spiral manner. Examples: Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output : 7 8 9 1 4 5 6 3 2 Input : 20 / \ 8 22 / \ / \ 5 3 4 25 / \ 10 14 Output : 10 14 20 5 3 4 25 22 8 Approach: The idea is to use two va
11 min read
Inorder Tree Traversal of Binary Tree in C++
A binary tree is a non-linear hierarchical data structure in which each node has at most two children known as the left child and the right child. As the binary tree has non-linear structure it can be traversed in multiple ways one such way is in-order traversal which is a depth first (DFS) traversa
4 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
Iterative Boundary Traversal of Complete Binary tree
Given a complete binary tree, the task is to traverse it such that all the boundary nodes are visited in Anti-Clockwise order starting from the root.Example: Input: Output: 1 2 4 5 6 7 3 Input: Output: 18 15 40 50 100 20 30Approach:Traverse left-most nodes of the tree from top to down. (Left boundar
9 min read
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
Zig Zag Level order traversal of a tree using single array
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 stacksThe idea behind this approach is first we have to take a queue, a dire
9 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
Binary Search Tree in C++
A Binary Search Tree (BST) is a type of binary tree in which the data is organized and stored in a sorted order. Unlike, a binary tree that doesn't follow a specific order for node placement, in a binary search tree all the elements on the left side of a node are smaller than the node itself, and el
10 min read
Print nodes in top view of Binary Tree | Set 2
Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes should be printed from left to right. Note: A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance
14 min read