using
System;
using
System.Collections.Generic;
public
class
GFG
{
public
class
Node
{
public
int
key;
public
Node left, right;
}
public
static
Node newNode(
int
data)
{
Node temp =
new
Node();
temp.key = data;
temp.left = temp.right =
null
;
return
temp;
}
static
List<
int
> stack_struct;
public
static
int
heightTree(Node root)
{
if
(root ==
null
)
return
0;
else
{
int
lheight = heightTree(root.left);
int
rheight = heightTree(root.right);
if
(lheight > rheight)
return
(1 + lheight);
else
return
(1 + rheight);
}
}
public
static
void
print_2_levels(Node root)
{
if
(root ==
null
)
return
;
int
height = heightTree(root);
int
count = 0;
for
(
int
i = 1; i < height + 1; i++)
{
stack_struct =
new
List<
int
>();
if
(count < 2)
print_level(root, i,
false
);
else
{
print_level(root, i,
true
);
for
(
int
j = stack_struct.Count - 1;
j >= 0; j--)
Console.Write(stack_struct[j] +
" "
);
if
(count == 3)
count = -1;
}
count += 1;
Console.WriteLine();
}
}
public
static
void
print_level(Node root,
int
level,
bool
stack)
{
if
(root ==
null
)
return
;
if
(level == 1 && stack ==
false
)
Console.Write(root.key +
" "
);
else
if
(level == 1 && stack ==
true
)
stack_struct.Add(root.key);
else
if
(level > 1)
{
print_level(root.left, level - 1, stack);
print_level(root.right, level - 1, stack);
}
}
public
static
void
Main(
string
[] args)
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.left.left.left = newNode(8);
root.left.left.right = newNode(9);
root.left.right.left = newNode(3);
root.left.right.right = newNode(1);
root.right.left.left = newNode(4);
root.right.left.right = newNode(2);
root.right.right.left = newNode(7);
root.right.right.right = newNode(2);
root.left.left.right.left = newNode(16);
root.left.right.right.left = newNode(17);
root.left.right.right.right = newNode(18);
root.right.left.right.right = newNode(19);
Console.WriteLine(
"Different levels:"
);
print_2_levels(root);
}
}