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.
Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs).
Return a list of all MHTs’ root labels. You can return the answer in any order.
The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
Example 1:
Input: n = 4, edges = [[1,0],[1,2],[1,3]]
Output: [1]
Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
Example 2:
Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
Output: [3,4]
Example 3:
Input: n = 1, edges = []
Output: [0]
Example 4:
Input: n = 2, edges = [[0,1]]
Output: [0,1]
Constraints:
1 <= n <= 2 * 104
edges.length == n - 1
0 <= ai, bi < n
ai != bi
All the pairs (ai, bi) are distinct.
The given input is guaranteed to be a tree and there will be no repeated edges.
题意
已知一棵树的n个节点,任何节点都可以作为根,求使得树高度最小的根的个数
思路
将树看做无向图,使用拓扑排序,优先入队的是度为1的节点(即叶子节点)
注1:最终结果只能是1或者2,因为若有3个根节点,必定有一个节点的度不为1,不能进行拓扑排序
注2:与正规的拓扑排序的区别
拓扑排序处理的是有向图,使用入度或出度标识,会自动识别到环,即当右向图中有不能继续往下拓扑的节点(入度都不为0,不能入队),则存在环
该题处理的是无向图,使用度标识,要手动识别环,即之前访问过的节点,要做标记,之后不可以再访问。否则一条边的两个顶点会互相访问。
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
if(n==1)return {0};
else if(n==2)return {0,1};
vector<int> G[21000];
int degree[21000]={0};
//建图,统计度
for(int i=0;i<edges.size();i++){
int a = edges[i][0];
int b = edges[i][1];
G[a].push_back(b);
G[b].push_back(a);
degree[a]++;
degree[b]++;
}
//以度为1的节点初始化队列
queue<int> q;
for(int i=0;i<n;i++)
if(degree[i]==1)q.push(i);
//拓扑排序
while(n>2){ //最终结果最多只有两个顶点
n-=q.size();
//易错点:不可以写for(int j=0;j<q.size();j++)
//因为在循环中q.push会修改q.size()的值,q.size()每轮都是变化的
for(int j=q.size();j>0;j--){
int v = q.front();
q.pop();
degree[v]=0; //标记为已访问
for(int i=0;i<G[v].size();i++){
int w = G[v][i];
if(degree[w]!=0){
degree[w]--;
if(degree[w]==1)q.push(w);
}
}
}
}
//队列中剩余的顶点即为答案
vector<int> ans;
while(!q.empty()){
ans.push_back(q.front());
q.pop();
}
return ans;
}
};