您的位置:首页 > 编程语言 > Java开发

Minimum Height Trees

2016-05-28 19:03 302 查看
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]

题意:

给一个数字n,代表了无向图的节点总数。然后给出该图中所有的边。找出以某个节点为根节点,使得树的高度最短。

思路:

最简单的暴力的方式就是尝试以每个节点作为根节点,然后使用广度优遍历的方法去遍历这个树的高度。不过这样的话时间复杂度就变成了O(n^2)。

换一个思路。我们知道在树中有叶子节点跟非叶子节点两种。叶子节点的度是1,即只有一个点与叶子节点相邻

(也或者只有一个节点的话就没有相邻的节点)。中间节点的度都>=2。

另一个知识就是去找一根绳子的长度,我们可以让两只蚂蚁从两端开始爬行,每次爬一步,若干步后它们相遇或者只差一步就说明找到了绳子的长度了。

结合上面的知识,我们使用这样的思路,让蚂蚁从各个叶子往中间爬,每次爬一步之后,丢弃上一个节点,

并且判断此时哪些成为了叶子节点,然后继续爬,直到最后两个蚂蚁相遇或者差一步就是最长的一个距离了。

这两个蚂蚁的位置就是根的位置,这个树最少要有这么高。

public List<Integer> findMinHeightTrees(int n, int[][] edges) {

List<Integer> list=new ArrayList<Integer>();

if(n<=0)return list;

else if(edges.length<=0){

for (int i=0;i<n;i++)

list.add(i);

return list;

}

Map<Integer, ArrayList<Integer>> graph = new HashMap<Integer,ArrayList<Integer>>();

for(int i=0;i<n;i++) graph.put(i, new ArrayList<Integer>());

int[] neighbors = new int
;

for(int[] edge :edges){//建立邻接表

neighbors[edge[0]]++;

neighbors[edge[1]]++;

graph.get(edge[0]).add(edge[1]);

graph.get(edge[1]).add(edge[0]);

}

for(int i=0;i<n;i++)

if(graph.get(i).size()==1)list.add(i);

while(n>2){

List<Integer> newList=new ArrayList<Integer>();

for(int l :list){

--n;

for(int nb :graph.get(l)){

if(--neighbors[nb]==1)newList.add(nb);

}

}

list=newList;

}

return list;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java