博客
关于我
【Lintcode】1298. Minimum Height Trees
阅读量:227 次
发布时间:2019-02-28

本文共 1997 字,大约阅读时间需要 6 分钟。

如何找到使树高最小的顶点编号

在一个具有树性质的无向图中,树高是从根节点到叶子节点的最长路径的长度加一。我们的目标是找到使得树高最小的顶点编号。这个问题可以通过广度优先搜索(BFS)来解决,类似于剥洋葱的过程,从外层逐层向内剥,最后一层即为答案。

步骤解释:

  • 特殊情况处理:如果图中只有一个顶点(n=1),则树高为1,顶点编号为0。

  • 图的构建:使用邻接表表示图,并计算每个顶点的度数。邻接表通过哈希表实现,快速查找相邻顶点。

  • 初始队列填充:将度数为1的顶点入队,因为这些顶点是叶子节点,可能作为根节点时树高最小。

  • BFS层序遍历:从队列中取出当前层的所有顶点,逐层扩展,记录每一层的顶点。每处理一个顶点,检查其相邻顶点,降低其度数。如果某个顶点的度数变为1,则将其加入下一层的队列中。

  • 结果收集:当队列为空时,最后记录的顶点即为树高最小的根节点。所有属于最后一层的顶点都作为答案返回。

  • 代码实现:

    import java.util.*;
    public class Solution {
    public List
    findMinHeightTrees(int n, int[][] edges) {
    List
    res = new ArrayList<>();
    if (n == 1) {
    res.add(0);
    return res;
    }
    Map
    > graph = buildGraph(edges);
    int[] degrees = getDegrees(n, edges);
    Queue
    queue = new LinkedList<>();
    for (int i = 0; i < n; i++) {
    if (degrees[i] == 1) {
    queue.offer(i);
    }
    }
    while (!queue.isEmpty()) {
    res.clear();
    int size = queue.size();
    for (int i = 0; i < size; i++) {
    int cur = queue.poll();
    res.add(cur);
    for (int next : graph.get(cur)) {
    degrees[next]--;
    if (degrees[next] == 1) {
    queue.offer(next);
    }
    }
    }
    }
    return res;
    }
    private int[] getDegrees(int n, int[][] edges) {
    int[] degrees = new int[n];
    for (int[] edge : edges) {
    degrees[edge[0]]++;
    degrees[edge[1]]++;
    }
    return degrees;
    }
    private Map
    > buildGraph(int[][] edges) {
    Map
    > graph = new HashMap<>(); for (int[] edge : edges) { graph.computeIfAbsent(edge[0], k -> new HashSet<>()).add(edge[1]); graph.computeIfAbsent(edge[1], k -> new HashSet<>()).add(edge[0]); } return graph; } }

    该算法的时间复杂度为O(n),空间复杂度为O(n)。通过BFS层序遍历,我们能够高效地找到使树高最小的顶点编号。

    转载地址:http://tgds.baihongyu.com/

    你可能感兴趣的文章
    Vue踩坑笔记 - 关于vue静态资源引入的问题
    查看>>
    Netty工作笔记0025---SocketChannel API
    查看>>
    Netty工作笔记0027---NIO 网络编程应用--群聊系统2--服务器编写2
    查看>>
    Netty工作笔记0050---Netty核心模块1
    查看>>
    Netty工作笔记0060---Tcp长连接和短连接_Http长连接和短连接_UDP长连接和短连接
    查看>>
    Netty工作笔记0077---handler链调用机制实例4
    查看>>
    Netty工作笔记0084---通过自定义协议解决粘包拆包问题2
    查看>>
    Netty常见组件二
    查看>>
    netty底层源码探究:启动流程;EventLoop中的selector、线程、任务队列;监听处理accept、read事件流程;
    查看>>
    Netty核心模块组件
    查看>>
    Netty框架的服务端开发中创建EventLoopGroup对象时线程数量源码解析
    查看>>
    Netty源码—2.Reactor线程模型一
    查看>>
    Netty源码—4.客户端接入流程一
    查看>>
    Netty源码—4.客户端接入流程二
    查看>>
    Netty源码—5.Pipeline和Handler一
    查看>>
    Netty源码—6.ByteBuf原理二
    查看>>
    Netty源码—7.ByteBuf原理三
    查看>>
    Netty源码—7.ByteBuf原理四
    查看>>
    Netty源码—8.编解码原理二
    查看>>
    Netty源码解读
    查看>>