题目描述:
For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.
Format
The graph contains n
nodes which are labeled from 0
to n - 1
. You will be given the number n
and a list of undirected edges
(each edge is a pair of labels).
You can assume that no duplicate edges will appear in edges
. Since all edges are undirected, [0, 1]
is the same as [1, 0]
and thus will not appear together in edges
.
Example 1 :
Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]]
0
|
1
/ \
2 3
Output: [1]
Example 2 :
Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
0 1 2
\ | /
3
|
4
|
5
Output: [3, 4]
Note:
- According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
- The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
给定一个树,可以选取任意节点作为根节点,求选取哪些节点为根节点时,树的高度最小。逐个选取根节点计算树高度的时间复杂度过高,可以先构建邻接表并计算每个节点的度,度为1说明是叶节点。那么从叶节点出发,向邻接点遍历,每次遍历对应的节点度数减一,如果度数变为1又可以加入队列,直到所有节点都访问到,那么最后一次遍历的一组节点就是所求。另外由于我们讨论的对象是树,也就是说每个节点最多有两个邻接点,且不存在环,那么最终满足要求的根节点只可能是1个或者2个,以此作为循环结束的依据。
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
if(n==1) return vector<int>(1,0);
vector<vector<int>> graph(n);
vector<int> degree(n,0);
for(int i=0;i<edges.size();i++)
{
degree[edges[i].first]++;
degree[edges[i].second]++;
graph[edges[i].first].push_back(edges[i].second);
graph[edges[i].second].push_back(edges[i].first);
}
queue<int> q;
for(int i=0;i<n;i++) if(degree[i]==1) q.push(i);
while(n>2)
{
int count=q.size();
n-=count;
for(int k=0;k<count;k++)
{
int i=q.front();
q.pop();
for(int j=0;j<graph[i].size();j++)
{
degree[graph[i][j]]--;
if(degree[graph[i][j]]==1) q.push(graph[i][j]);
}
}
}
vector<int> result;
while(!q.empty())
{
result.push_back(q.front());
q.pop();
}
return result;
}
};