# Middle-题目85：310. Minimum Height Trees

63人阅读 评论(0)

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:
Given n = 4, edges = [[1, 0], [1, 2], [1, 3]]

    0
|
1
/ \
2   3


return [1]
Example 2:
Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]

 0  1  2
\ | /
3
|
4
|
5


return [3, 4]

public class Solution {
public  List<Integer> findMinHeightTrees(int n, int[][] edges) {
Map<Integer, Set<Integer>> adjList = new HashMap<Integer,Set<Integer>>();
boolean[] isLeaf = new boolean[n];
int[] degrees = new int[n];
int nextVertical = 0, currentVerticals = n;
for(int i = 0; i<n;i++)
for(int[] edge : edges) {
degrees[edge[0]]++;
degrees[edge[1]]++;
}
while(currentVerticals > 2) {
for(int i = 0;i<n;i++) {
if(degrees[i]==1) {
isLeaf[i] = true;
}
}
for(int i = 0;i<n;i++) {
if(isLeaf[i]) {
degrees[i]--;
degrees[nextVertical]--;
if(degrees[i]==0)
currentVerticals--;
if(degrees[nextVertical]==0)
currentVerticals--;
isLeaf[i] = false;
}
}
}
List<Integer> list = new ArrayList<Integer>();
}
if(n==1)
if(currentVerticals==0)
return list;
}
}

public class Solution {
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
if (n == 1)
return Collections.singletonList(0);
for (int i = 0; i < n; i++)
for (int[] edge : edges) {
}

List<Integer> leaves = new ArrayList<>();
for (int i = 0; i < n; i++)

while (n > 2) {
n -= leaves.size();
List<Integer> newLeaves = new ArrayList<>();
for (int i : leaves) {
}
leaves = newLeaves;
}
return leaves;
}
}

Cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：56308次
• 积分：3204
• 等级：
• 排名：第10668名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论