Leetcode 310. Minimum Height Trees

题目:node

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.app

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).code

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.orm

解法:
由于树就是两个点被一条线连接的无向图,因此先用一个list把树存成无向图的列表。能够从头边同时进行,查看叶子节点并加入到叶子节点链表(遍历一遍后,叶子节点链表size 为1)。 将叶子节点保存下来。这些叶子节点不用再查,可是剩余的中间节点,要依次查看,把跟第一层叶子节点有关的图的矩阵里对应的记录所有删除,相似于剥除最外面一圈全部的点。 这个时候就会有第二层叶子节点(那些在列表当中size为1的点),用一样的方法进行剥除。最后留在叶子节点list里面的点便可觉得根。rem

代码:get

public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> leaves = new ArrayList<>();
        if (n == 1) {
            leaves.add(0);
            return leaves;
        }
        
        List<Set<Integer>> adj = new ArrayList<>();
        for(int i = 0; i < n; i++) adj.add(new HashSet<>());
        for(int[] edge : edges){
            adj.get(edge[0]).add(edge[1]);
            adj.get(edge[1]).add(edge[0]);
        }
        for(int i = 0; i < n; i++) 
         if(adj.get(i).size()==1) leaves.add(i);
        while(n > 2){
            n-=leaves.size();
            List<Integer> newLeaves = new ArrayList<>();
            for(int i : leaves){
                for(int j : adj.get(i)){
                    adj.get(j).remove(i);
                    if(adj.get(j).size() ==1) newLeaves.add(j);
                }
            }
            leaves = newLeaves;
        }
        return leaves;
    }
相关文章
相关标签/搜索