using
System;
class
node
{
public
int
data;
public
node left;
public
node right;
public
node leftNeighbour;
public
node(
int
data)
{
this
.data = data;
this
.left =
null
;
this
.right =
null
;
this
.leftNeighbour =
null
;
}
}
class
GFG
{
static
node root;
static
node[] a =
new
node[100];
static
void
connectNodes(node p,
int
l)
{
if
(p ==
null
)
{
return
;
}
p.leftNeighbour = a[l];
a[l] = p;
connectNodes(p.left, l + 1);
connectNodes(p.right, l + 1);
}
static
void
connectNodesUtil(node root)
{
for
(
int
i = 0; i < 100; i++)
{
a[i] =
new
node(-1);
}
connectNodes(root, 0);
Console.WriteLine(
"Following are populated leftNeighbour"
+
" pointers in the tree:"
);
Console.WriteLine(
"leftNeighbour of "
+ root.data +
" is "
+ (root.leftNeighbour !=
null
?
root.leftNeighbour.data : -1));
Console.WriteLine(
"leftNeighbour of "
+ root.left.data +
" is "
+ (root.left.leftNeighbour !=
null
?
root.left.leftNeighbour.data : -1));
Console.WriteLine(
"leftNeighbour of "
+ root.right.data +
" is "
+ (root.right.leftNeighbour !=
null
?
root.right.leftNeighbour.data : -1) );
Console.WriteLine(
"leftNeighbour of "
+ root.left.left.data +
" is "
+ (root.left.left.leftNeighbour !=
null
?
root.left.left.leftNeighbour.data : -1));
}
static
public
void
Main ()
{
GFG.root =
new
node(10);
GFG.root.left =
new
node(8);
GFG.root.right =
new
node(2);
GFG.root.left.left =
new
node(3);
connectNodesUtil(root);
}
}