考察点:图,遍历,bfs,路径;
思路:这个题就是从叶子节点开始遍历,去除掉当前所有的叶子节点后,再从新图的叶子节点开始遍历,直到最后剩下一个或者两个叶子节点,就是最深的那个点。
C++ 代码:
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
unordered_map<int, unordered_set<int>> mp;
vector<int> leaves;
if (n == 1) {
leaves.push_back(0);
return leaves;
}
for (auto &item : edges) {
mp[item.first].insert(item.second);
mp[item.second].insert(item.first);
}
queue<int> q;
int level[n];
for (int i=0; i<n; i++) {
if (mp[i].size() == 1) {
leaves.push_back(i);
}
}
while (n > 2) {
n -= leaves.size();
vector<int> nextleaves;
for (int i=0; i<leaves.size(); i++) {
int nextNode = *(mp[leaves[i]].begin());
mp[leaves[i]].erase(nextNode);
mp[nextNode].erase(leaves[i]);
if (mp[nextNode].size() == 1) {
nextleaves.push_back(nextNode);
}
}
leaves = nextleaves;
}
return leaves;
}
};