310. Minimum Height Trees

来源:互联网 发布:数据库的导入和导出 编辑:程序博客网 时间:2024/06/07 14:28

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

        0        |        1       / \      2   3

return [1]

Example 2:

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

     0  1  2      \ | /        3        |        4        |        5

return [3, 4]


给出无向图中各边的数组,从中找出一个点作为树的根节点使树有最小的高度


思路:一棵树,把所有的根节点去掉不影响找这棵树的root,一层一层把叶子节点去掉。

怎么保证这样找出来的一定是最小的高度树呢? 剩下的点一定是层数最高的点,按照我们的找法在每次处理时都已经将最多的叶节点去掉了剩下的就是最合要求的

graph是一个hashmap,找出每个节点的相邻节点 如果某个节点的相邻节点只含有一个节点说明这是一个叶节点把它保存到leaves这个list中。遍历list,将其中的每个节点从graph对应处去掉,与这个节点相邻的节点去掉,对应的set是空集,同时从原来与这个叶节点相邻的节点的集合中把这个叶节点删掉 找到最后剩下的一个或者两个节点就是我们想要的root节点

public class Solution {    public List<Integer> findMinHeightTrees(int n, int[][] edges) {        if(n<=1) return Collections.singletonList(0);//这种小写法还要注意直接返回空数组还不对。。。        List<Integer> leaves=new ArrayList<Integer>();                HashMap<Integer,Set<Integer>> graph=new HashMap<Integer,Set<Integer>>();        for(int i=0;i<n;i++){            graph.put(i,new HashSet<Integer>());        }        for(int []edge:edges){            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)                leaves.add(i);        }        while(n>2){            n-=leaves.size();            List<Integer> newleaves=new ArrayList<Integer>();            for(int leaf:leaves){                for(int newleaf:graph.get(leaf)){                    graph.get(leaf).remove(newleaf);                    graph.get(newleaf).remove(leaf);                    if(graph.get(newleaf).size()==1)                        newleaves.add(newleaf);                }            }            leaves=newleaves;        }        return leaves;    }}







0 0
原创粉丝点击