// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
// To create tree
map<int, vector<int> > tree;
// Function to store the path
// from given vertex to the target
// vertex in a vector path
bool getDiameterPath(int vertex,
int targetVertex,
int parent,
vector<int>& path)
{
// If the target node is found,
// push it into path vector
if (vertex == targetVertex) {
path.push_back(vertex);
return true;
}
for (auto i : tree[vertex]) {
// To prevent visiting a
// node already visited
if (i == parent)
continue;
// Recursive call to the neighbours
// of current node inorder
// to get the path
if (getDiameterPath(i, targetVertex,
vertex, path)) {
path.push_back(vertex);
return true;
}
}
return false;
}
// Function to obtain and return the
// farthest node from a given vertex
void farthestNode(int vertex, int parent,
int height, int& maxHeight,
int& maxHeightNode)
{
// If the current height is maximum
// so far, then save the current node
if (height > maxHeight) {
maxHeight = height;
maxHeightNode = vertex;
}
// Iterate over all the neighbours
// of current node
for (auto i : tree[vertex]) {
// This is to prevent visiting
// a already visited node
if (i == parent)
continue;
// Next call will be at 1 height
// higher than our current height
farthestNode(i, vertex,
height + 1,
maxHeight,
maxHeightNode);
}
}
// Function to add edges
void addedge(int a, int b)
{
tree[a].push_back(b);
tree[b].push_back(a);
}
void FindCenter(int n)
{
// Now we will find the 1st farthest
// node from 0(any arbitrary node)
// Perform DFS from 0 and update
// the maxHeightNode to obtain
// the farthest node from 0
// Reset to -1
int maxHeight = -1;
// Reset to -1
int maxHeightNode = -1;
farthestNode(0, -1, 0, maxHeight,
maxHeightNode);
// Stores one end of the diameter
int leaf1 = maxHeightNode;
// Similarly the other end of
// the diameter
// Reset the maxHeight
maxHeight = -1;
farthestNode(maxHeightNode,
-1, 0, maxHeight,
maxHeightNode);
// Stores the second end
// of the diameter
int leaf2 = maxHeightNode;
// Store the diameter into
// the vector path
vector<int> path;
// Diameter is equal to the
// path between the two farthest
// nodes leaf1 and leaf2
getDiameterPath(leaf1, leaf2,
-1, path);
int pathSize = path.size();
if (pathSize % 2) {
cout << path[pathSize / 2]
<< endl;
}
else {
cout << path[pathSize / 2]
<< ", "
<< path[(pathSize - 1) / 2]
<< endl;
}
}
// Driver Code
int main()
{
int N = 4;
addedge(1, 0);
addedge(1, 2);
addedge(1, 3);
FindCenter(N);
return 0;
}