Leetcode 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.
解法:
因为树就是两个点被一条线链接的无向图,所以先用一个list把树存成无向图的列表。可以从头边同时进行,查看叶子节点并加入到叶子节点链表(遍历一遍后,叶子节点链表size 为1)。 将叶子节点保存下来。这些叶子节点不用再查,但是剩余的中间节点,要依次查看,把跟第一层叶子节点有关的图的矩阵里对应的记录全部删除,类似于剥除最外面一圈所有的点。 这个时候就会有第二层叶子节点(那些在列表当中size为1的点),用同样的方法进行剥除。最后留在叶子节点list里面的点即可以为根。
代码:
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;
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论