using
System;
using
System.Collections;
using
System.Collections.Generic;
class
GFG{
public
class
Node
{
public
Node left;
public
Node right;
public
int
data;
};
public
static
Node newNode(
int
data)
{
Node temp =
new
Node();
temp.data = data;
temp.left =
null
;
temp.right =
null
;
return
temp;
}
static
void
printPath(
int
Data,
Dictionary<
int
,
int
> parent)
{
if
(parent[Data] == Data)
return
;
printPath(parent[Data], parent);
Console.Write(parent[Data] +
" "
);
}
static
void
leftMostShortest(Node root)
{
Queue q =
new
Queue();
q.Enqueue(root);
int
LeafData = -1;
Node temp =
null
;
Dictionary<
int
,
int
> parent =
new
Dictionary<
int
,
int
>();
parent[root.data] = root.data;
while
(q.Count != 0)
{
temp = (Node)q.Dequeue();
if
(temp.left ==
null
&&
temp.right ==
null
)
{
LeafData = temp.data;
break
;
}
else
{
if
(temp.left !=
null
)
{
q.Enqueue(temp.left);
parent[temp.left.data] = temp.data;
}
if
(temp.right !=
null
)
{
q.Enqueue(temp.right);
parent[temp.right.data] = temp.data;
}
}
}
printPath(LeafData, parent);
Console.Write(LeafData +
" "
);
}
public
static
void
Main(
string
[] args)
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.right.left = newNode(5);
root.right.right = newNode(7);
root.left.left.left = newNode(10);
root.left.left.right = newNode(11);
root.right.right.left = newNode(8);
leftMostShortest(root);
}
}