DFS+BFS:
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
int n;
vector<int>u,v,f,ne;
vector<bool>book;
vector<int>ml;
int c = 0, mle=0;
void cbfs(int bh) {
c++;
int i;
queue<int>r;
r.push(bh);
while (!r.empty()) {
book[r.front()] = true;
for (i = f[r.front()]; i != -1; i = ne[i]) {
if (book[v[i]])
continue;
r.push(v[i]);
}
r.pop();
}
return;
}
void dfs(int cur, int l) {
int i;
mle = (mle >= l) ? mle : l;
for (i = f[cur]; i != -1; i = ne[i]) {
if (!book[v[i]]) {
book[v[i]] = true;
dfs(v[i], l + 1);
book[v[i]] = false;
}
}
return;
}
void mldfs() {
int i, j;
for (i = 1; i <= n; i++) {
mle = 0;
book= vector<bool>(n + 1, false);
book[i] = true;
dfs(i,0);
ml[i] = mle;
}
return;
}
int main() {
int i,j=0;
cin >> n;
f = vector<int>(n + 1, -1);
book = vector<bool>(n + 1, false);
ml = vector<int>(n + 1);
for (i = 1; i <= n - 1; i++) {
int x1, x2;
cin >> x1 >> x2;
u.push_back(x1);
v.push_back(x2);
ne.push_back(f[x1]);
f[x1] = j;
j++;
u.push_back(x2);
v.push_back(x1);
ne.push_back(f[x2]);
f[x2] = j;
j++;
}
for (i = 1; i <= n; i++) {
if (!book[i])
cbfs(i);
}
if(c!=1)
printf("Error: %d components", c);
else {
mldfs();
for (i = 1; i <= n; i++) {
if (ml[i] == mle)
cout << i << endl;
}
}
return 0;
}