using
System;
using
System.Collections.Generic;
class
GFG {
static
Dictionary<
int
, List<
int
>> tree;
static
List<
int
> path;
static
int
maxHeight, maxHeightNode;
static
bool
getDiameterPath(
int
vertex,
int
targetVertex,
int
parent,
List<
int
> path)
{
if
(vertex == targetVertex)
{
path.Add(vertex);
return
true
;
}
foreach
(
int
i
in
tree[vertex])
{
if
(i == parent)
continue
;
if
(getDiameterPath(i, targetVertex,
vertex, path))
{
path.Add(vertex);
return
true
;
}
}
return
false
;
}
static
void
farthestNode(
int
vertex,
int
parent,
int
height)
{
if
(height > maxHeight)
{
maxHeight = height;
maxHeightNode = vertex;
}
if
(tree.ContainsKey(vertex) && tree[vertex].Count > 0)
{
foreach
(
int
i
in
tree[vertex])
{
if
(i == parent)
continue
;
farthestNode(i, vertex, height + 1);
}
}
}
static
void
addedge(
int
a,
int
b)
{
if
(!tree.ContainsKey(a))
tree[a] =
new
List<
int
>();
tree[a].Add(b);
if
(!tree.ContainsKey(b))
tree[b] =
new
List<
int
>();
tree[b].Add(a);
}
static
void
FindCenter(
int
n)
{
maxHeight = -1;
maxHeightNode = -1;
farthestNode(0, -1, 0);
int
leaf1 = maxHeightNode;
maxHeight = -1;
farthestNode(maxHeightNode,
-1, 0);
int
leaf2 = maxHeightNode;
path =
new
List<
int
>();
getDiameterPath(leaf1, leaf2,
-1, path);
int
pathSize = path.Count;
if
(pathSize % 2 == 1)
{
Console.WriteLine(path[pathSize / 2]);
}
else
{
Console.WriteLine(path[pathSize / 2] +
", "
+ path[(pathSize - 1) / 2]);
}
}
static
void
Main() {
int
N = 4;
tree =
new
Dictionary<
int
, List<
int
>>();
addedge(1, 0);
addedge(1, 2);
addedge(1, 3);
FindCenter(N);
}
}