最小高度树
思路:本质上是找到树中的最长路径。当最长路径上中间点(若路经长为偶数,则中间点仅有一个,否者中间点有两个)作为根时,此时树高最小。
Code:
class Solution {
public:
//拓扑排序
int d[20010];
queue<pair<int,int>> q;
vector<int> e[20010];
bool vis[20010];
vector<pair<int,int>> res;
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
vector<int> ans;
if(n==1) {
ans.push_back(0);
return ans;
}
for(int i=0;i<edges.size();i++) {
e[edges[i][0]].push_back(edges[i][1]);
e[edges[i][1]].push_back(edges[i][0]);
d[edges[i][0]]++;
d[edges[i][1]]++;
}
for(int i=0;i<n;i++) {
if(d[i]==1) {
q.push({i,0});
res.push_back({0,i});
vis[i] = 1;
}
}
while(q.size()) { //bfs
int k = q.front().first;
int dis = q.front().second;
q.pop();
for(int i=0;i<e[k].size();i++) {
d[e[k][i]]--;
if(d[e[k][i]] == 1 && !vis[e[k][i]]) {
q.push({e[k][i],dis+1});
res.push_back({dis+1,e[k][i]});
vis[e[k][i]] = 1;
}
}
}
sort(res.begin(),res.end());
ans.push_back(res[n-1].second);
if(res[n-1].first == res[n-2].first) ans.push_back(res[n-2].second);
return ans;
}
};