using
System;
using
System.Collections.Generic;
using
System.Collections;
class
GFG{
static
int
sz = 100000;
static
int
maxLevel = 0;
static
ArrayList []tree =
new
ArrayList[sz + 1];
static
bool
[]vis =
new
bool
[sz + 1];
static
int
[]level =
new
int
[sz + 1];
static
ArrayList []nodes =
new
ArrayList[sz + 1];
static
void
addEdge(
int
a,
int
b)
{
tree[a].Add(b);
tree[b].Add(a);
}
static
void
bfs(
int
node)
{
Queue qu =
new
Queue();
qu.Enqueue(
new
KeyValuePair<
int
,
int
>(node, 0));
nodes[0].Add(node);
vis[node] =
true
;
level[1] = 0;
while
(qu.Count != 0)
{
KeyValuePair<
int
,
int
> p = (KeyValuePair<
int
,
int
>)qu.Peek();
qu.Dequeue();
vis[p.Key] =
true
;
foreach
(
int
child
in
tree[p.Key])
{
if
(!vis[child])
{
qu.Enqueue(
new
KeyValuePair<
int
,
int
>(
child, p.Key));
level[child] = level[p.Key] + 1;
maxLevel = Math.Max(maxLevel,
level[child]);
nodes[level[child]].Add(child);
}
}
}
}
static
void
display()
{
bool
flag =
true
;
int
p1 = 0, p2 = maxLevel;
int
i = nodes[p1].Count - 1, j = 0;
while
(p1 <= p2)
{
if
(flag)
{
Console.Write((
int
)nodes[p1][i] +
" "
);
i--;
if
(i < 0)
{
p1++;
i = nodes[p1].Count - 1;
}
}
else
{
Console.Write((
int
)nodes[p2][j] +
" "
);
j++;
if
(j >= nodes[p2].Count)
{
p2--;
j = 0;
}
}
flag = !flag;
if
(p1 >= p2 && i < j)
{
break
;
}
}
}
public
static
void
Main(
string
[] args)
{
for
(
int
i = 0; i < sz + 1; i++)
{
tree[i] =
new
ArrayList();
nodes[i] =
new
ArrayList();
vis[i] =
false
;
level[i] = 0;
}
addEdge(1, 2);
addEdge(1, 3);
addEdge(2, 4);
addEdge(3, 5);
addEdge(3, 6);
addEdge(4, 7);
addEdge(6, 8);
bfs(1);
display();
}
}