这道题第一遍做的时候没什么思路,现在再做感觉不难...
没必要考虑太多,只有叶子节点才有可能成为最深的节点,
只要判断所有叶子节点就可以了。
注意有一个测试节点N为1,需要特殊考虑
#include <iostream>
#include <vector>
#include <map>
#include <cstring>
using namespace std;
bool visited[10005];
int maxDepth;
vector<vector<int >> graph;
void dfs(int val,int depth){
visited[val]= true;
if(depth>maxDepth){
maxDepth=depth;
}
for(int x:graph[val]){
if(!visited[x]){
dfs(x,depth+1);
}
}
}
int main() {
int N;
cin>>N;
graph.resize(N+1);
if(N==1){
cout<<1<<endl;
}
for (int i = 0; i < N - 1; ++i) {
int a,b;
cin>>a>>b;
graph[a].push_back(b);
graph[b].push_back(a);
}
memset(visited, false, sizeof(visited));
maxDepth=-1;
int count=0;
for (int i = 1; i <=N; ++i) {
if(!visited[i]){
dfs(i,0);
count++;
}
}
if(count>1){
cout<<"Error: "<<count<<" components"<<endl;
return 0;
}
int maxval=-1;
vector<int> vector1;
for (int i = 1; i <=N; ++i) {
if(graph[i].size()==1){
memset(visited, false, sizeof(visited));
maxDepth=-1;
dfs(i,0);
if(maxDepth>maxval){
maxval=maxDepth;
vector1.clear();
vector1.push_back(i);
} else if(maxval==maxDepth){
vector1.push_back(i);
}
}
}
for(int x:vector1){
printf("%d\n",x);
}
return 0;
}