原题地址:https://leetcode-cn.com/problems/minimum-height-trees/
题目描述:
对于一个具有树特征的无向图,我们可选择任何一个节点作为根。图因此可以成为树,在所有可能的树中,具有最小高度的树被称为最小高度树。给出这样的一个图,写出一个函数找到所有的最小高度树并返回他们的根节点。
格式
该图包含 n 个节点,标记为 0 到 n - 1。给定数字 n 和一个无向边 edges 列表(每一个边都是一对标签)。
你可以假设没有重复的边会出现在 edges 中。由于所有的边都是无向边, [0, 1]和 [1, 0] 是相同的,因此不会同时出现在 edges 里。
示例 1:
输入: n = 4, edges = [[1, 0], [1, 2], [1, 3]]
0
|
1
/ \
2 3
输出: [1]
示例 2:
输入: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
0 1 2
\ | /
3
|
4
|
5
输出: [3, 4]
说明:
根据树的定义,树是一个无向图,其中任何两个顶点只通过一条路径连接。 换句话说,一个任何没有简单环路的连通图都是一棵树。
树的高度是指根节点和叶子节点之间最长向下路径上边的数量。
解题方案:
这题是关于图的建立,以及使用广度优先遍历进行搜索最小高度树。
代码:
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
map<int, set<int> > graph;
graph.insert(make_pair(0, set<int>()));
for (auto e : edges) {
if (graph.find(e.first) == graph.end())
graph.insert(make_pair(e.first, set<int>()));
graph[e.first].insert(e.second);
if (graph.find(e.second) == graph.end())
graph.insert(make_pair(e.second, set<int>()));
graph[e.second].insert(e.first);
}
queue<int> leaves, newLeaves;
for (auto node : graph)
if (node.second.size() == 1)
leaves.push(node.first);
while (graph.size() > 2 || (graph.size() == 2 && leaves.size() != 2)) {
int leaf = leaves.front();
leaves.pop();
int neighbor = *(graph[leaf].begin());
graph[neighbor].erase(leaf);
if (graph[neighbor].size() == 1)
newLeaves.push(neighbor);
graph.erase(leaf);
if (leaves.empty()) {
leaves = newLeaves;
newLeaves = queue<int>();
}
}
vector<int> ans;
for (auto node : graph) {
ans.push_back(node.first);
}
return ans;
}
};