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);
}
}