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++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
struct Node *left, *right;
};
Node* newNode( int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
int findHeight( struct Node* node)
{
if (node == NULL) return 0;
int leftHeight = findHeight(node->left);
int rightHeight = findHeight(node->right);
return 1+(leftHeight > rightHeight ? leftHeight : rightHeight );
}
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);
}
void BFS( int ** mtrx, struct Node* node)
{
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();
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;
}
}
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++) {
if (mtrx[k1][j] != INT_MAX) {
cout << mtrx[k1][j] << ", " ;
}
}
k2 = 0;
k1++;
for (j = k4; j >= 0; j--) {
if (mtrx[k3][j] != INT_MAX) {
cout << mtrx[k3][j] << ", " ;
}
}
k4 = width - 1;
k3--;
}
if (height % 2 != 0) {
for (j = k2; j < width; j++) {
if (mtrx[k1][j] != INT_MAX) {
cout << mtrx[k1][j] << ", " ;
}
}
}
}
void printPattern( struct Node* node)
{
int max_value = INT_MIN;
int min_value = INT_MAX;
int hd = 0;
findWidth(node, max_value, min_value, hd);
int width = max_value + abs (min_value);
int height = findHeight(node);
int ** mtrx = new int *[height];
for ( int i = 0; i < height; i++) {
mtrx[i] = new int [width];
}
for ( int i = 0; i < height; i++) {
for ( int j = 0; j < width; j++) {
mtrx[i][j] = INT_MAX;
}
}
BFS(mtrx, node);
traverse_matrix(mtrx, height, width);
free (mtrx);
}
int main()
{
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;
}
|
Java
import java.util.*;
class Node {
int key;
Node left, right;
Node( int key)
{
this .key = key;
left = right = null ;
}
}
class BinaryTree {
Node root;
int findHeight(Node node)
{
if (node == null )
return 0 ;
int leftHeight = findHeight(node.left);
int rightHeight = findHeight(node.right);
return 1
+ (leftHeight > rightHeight ? leftHeight
: rightHeight);
}
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 );
}
void BFS( int [][] mtrx, Node node)
{
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();
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 ;
}
}
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++) {
if (mtrx[k1][j] != Integer.MAX_VALUE) {
System.out.print(mtrx[k1][j] + ", " );
}
}
k2 = 0 ;
k1++;
for (j = k4; j >= 0 ; j--) {
if (mtrx[k3][j] != Integer.MAX_VALUE) {
System.out.print(mtrx[k3][j] + ", " );
}
}
k4 = width - 1 ;
k3--;
}
if (height % 2 != 0 ) {
for (j = k2; j < width; j++) {
if (mtrx[k1][j] != Integer.MAX_VALUE) {
System.out.print(mtrx[k1][j] + ", " );
}
}
}
}
void printPattern(Node node)
{
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 ;
findWidth(node, max_value, min_value, hd);
int width = max_value[ 0 ] + Math.abs(min_value[ 0 ]);
int height = findHeight(node);
int [][] mtrx = new int [height][width];
for ( int i = 0 ; i < height; i++) {
for ( int j = 0 ; j < width; j++) {
mtrx[i][j] = Integer.MAX_VALUE;
}
}
BFS(mtrx, node);
traverse_matrix(mtrx, height, width);
}
public static void main(String[] args)
{
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);
}
}
|
Python3
INT_MAX = 2 * * 31
INT_MIN = - 2 * * 31
class newNode:
def __init__( self , data):
self .key = data
self .left = None
self .right = None
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 )
def BFS(mtrx,node):
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 ]
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
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):
if (mtrx[k1][j] ! = INT_MAX):
print (mtrx[k1][j], ", " , end = "")
k2 = 0
k1 + = 1
for j in range (k4, - 1 , - 1 ):
if (mtrx[k3][j] ! = INT_MAX):
print (mtrx[k3][j], ", " , end = "")
k4 = width - 1
k3 - = 1
if (width % 2 ! = 0 ):
for j in range (k2, width):
if (mtrx[k1][j] ! = INT_MAX):
print (mtrx[k1][j], ", " , end = "")
def printPattern(node):
max_value = [INT_MIN]
min_value = [INT_MAX ]
hd = 0
findWidth(node, max_value, min_value, hd)
width = max_value[ 0 ] + abs (min_value[ 0 ])
mtrx = [ 0 ] * width
for i in range (width):
mtrx[i] = [ 0 ] * width
for i in range (width):
for j in range (width):
mtrx[i][j] = INT_MAX
BFS(mtrx, node)
traverse_matrix(mtrx, width)
if __name__ = = '__main__' :
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)
|
C#
using System;
using System.Collections.Generic;
class Node {
public int key;
public Node left, right;
public Node( int key)
{
this .key = key;
left = right = null ;
}
}
class BinaryTree {
public Node root;
public int findHeight(Node node)
{
if (node == null )
return 0;
int leftHeight = findHeight(node.left);
int rightHeight = findHeight(node.right);
return 1
+ (leftHeight > rightHeight ? leftHeight
: rightHeight);
}
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);
}
public void BFS( int [, ] mtrx, Node node)
{
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();
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;
}
}
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++) {
if (mtrx[k1, j] != int .MaxValue) {
Console.Write(mtrx[k1, j] + ", " );
}
}
k2 = 0;
k1++;
for (j = k4; j >= 0; j--) {
if (mtrx[k3, j] != int .MaxValue) {
Console.Write(mtrx[k3, j] + ", " );
}
}
k4 = width - 1;
k3--;
}
if (height % 2 != 0) {
for (j = k2; j < width; j++) {
if (mtrx[k1, j] != int .MaxValue) {
Console.Write(mtrx[k1, j] + ", " );
}
}
}
}
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);
}
public static void Main( string [] args)
{
BinaryTree tree = new BinaryTree();
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>
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);
</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).
|