算法
(拓扑排序) $O(n + e)$
首先我们将所有的叶子节点都放入队列中,之后每次有点从队列中出来,就将和这个点相邻的没有入队过的点加入到队列中. 容易想到,答案的数量最多不超过两个,所以只要比较最后两个出队的点即可.
C++ 代码
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
if (edges.empty()) {
return vector<int>(1, 0);
}
vector<int> indegrees(n, 0);
vector<vector<int>> outdegrees(n, vector<int>());
for (int i = 0; i < edges.size(); ++i) {
indegrees[edges[i][0]]++;
indegrees[edges[i][1]]++;
outdegrees[edges[i][0]].push_back(edges[i][1]);
outdegrees[edges[i][1]].push_back(edges[i][0]);
}
queue<int> que;
unordered_set<int> visited;
for (int i = 0; i < n; ++i) {
if (indegrees[i] == 1) {
que.push(i);
visited.insert(i);
}
}
vector<int> ans;
while (!que.empty()) {
ans.clear();
int size = que.size();
for (int i = 0; i < size; ++i) {
int curr = que.front();
ans.push_back(curr);
que.pop();
for (int j = 0; j < outdegrees[curr].size(); ++j) {
int sub = outdegrees[curr][j];
if (visited.find(sub) != visited.end()) {
continue;
}
indegrees[sub]--;
if (indegrees[sub] == 1) {
que.push(sub);
visited.insert(sub);
}
}
}
}
return ans;
}
};