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

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的碎碎念：

• 本文已收录于以下专栏：

## Leetcode: 310.Minimum Height Trees

Leetcode: 310.Minimum Height Trees

## 【LEETCODE】310-Minimum Height Trees

For a undirected graph with tree characteristics, we can choose any node as the root. The result gra...

## [leetcode] 310.Minimum Height Trees

leetcode 310.Minimum Height Trees

## leetcode 310. Minimum Height Trees

For a undirected graph with tree characteristics, we can choose any node as the root. The result gra...

## leetcode 310. Minimum Height Trees 解题报告

• jly0612
• 2016年09月04日 17:08
• 351

## 【Leetcode】310. Minimum Height Trees

Description:For a undirected graph with tree characteristics, we can choose any node as the root. Th...

## LeetCode-310. Minimum Height Trees (JAVA) 图中最矮的树

LeetCode-310. Minimum Height Trees (JAVA) 图中最矮的树

举报原因： 您举报文章：Middle-题目85：310. Minimum Height Trees 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)