前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode310. Minimum Height Trees

leetcode310. Minimum Height Trees

作者头像
眯眯眼的猫头鹰
发布2019-03-13 16:44:43
5690
发布2019-03-13 16:44:43
举报
文章被收录于专栏:眯眯眼猫头鹰的小树杈

题目

代码语言:javascript
复制
For an 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 :

Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]]

        0
        |
        1
       / \
      2   3 

Output: [1]
Example 2 :

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

     0  1  2
      \ | /
        3
        |
        4
        |
        5 

Output: [3, 4]
Note:

According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

在无向图的生成树中,我们可以指定任何一个节点为这棵树的根节点。现在要求在这样一棵生成树中,找到生成树的高度最低的所有根节点。

其实,决定一棵树的高度往往是树中的最长路径,只有我们选择最长路径的中间点才能够尽可能减少树的高度。那么我们如何找到所有的中间节点呢?

当出发点只有两个时,我们知道中间节点就是从出发点同时出发,当二者相遇或者二者只间隔一个位置是所在的点就是两个出发点的重点。那么多个出发点也是同样的道理,每个人从各个出发点出发,最终相遇的点就是我们所要找的中间点。

这题的思路有些类似于拓扑排序,每次我们都会去除所有入度为0的点,因为这些点肯定是叶节点。然后不停的往中间走,直到剩下最后一个叶节点或是最后两个叶节点。

代码语言:javascript
复制
  0
  |
  1
 / \
2   3

这个图中删除所有入度为0的点就只剩下1,因此我们知道1一定就是我们所要求的根节点

思路一:图论

这一种解法着重强调了利用图论中的数据结构来解决问题。这里我们采用图论中的邻接表来存储图中的点和边。然后利用邻接表的相关属性来判断当前节点是否是叶节点。

代码语言:javascript
复制
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        if(n==1) return Collections.singletonList(0);
        //初始化邻接表
        List<Set<Integer>> adj = new ArrayList<Set<Integer>>();
        for(int i = 0 ; i<n ; i++) {
            adj.add(new HashSet<Integer>());
        }
        for(int[] edge : edges) {
            adj.get(edge[0]).add(edge[1]);
            adj.get(edge[1]).add(edge[0]);
        }
        
        List<Integer> leaves = new ArrayList<Integer>();
        for(int i = 0 ; i<adj.size() ; 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) {
                int j = adj.get(i).iterator().next();
                adj.get(j).remove(i);
                if (adj.get(j).size() == 1) newLeaves.add(j);
            }
            leaves = newLeaves;
        }
        return leaves;
    }

思路二:简化数据结构

这里使用degree数组存储每个顶点的度数,即连接的变数。度数为一的顶点就是叶节点。再用connected存储每个顶点所连接的所有边的异或值。这里使用异或的原因是对同一个值进行两次异或即可以回到最初值。

代码语言:javascript
复制
    public List<Integer> findMinHeightTrees2(int n, int[][] edges) {
        if(n==1) return Collections.singletonList(0);
        int[] connected = new int[n];
        int[] degree = new int[n];
        
        for(int[] edge : edges) {
            int v1 = edge[0];
            int v2 = edge[1];
            connected[v1] ^= v2;
            connected[v2] ^= v1;
            
            degree[v1]++;
            degree[v2]++;
        }
        
        LinkedList<Integer> queue = new LinkedList<Integer>();
        for(int i = 0 ; i<degree.length ; i++) {
            if(degree[i] == 1) {
                queue.offer(i);
            }
        }
        
        while(n > 2 && !queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0 ; i<size ; i++) {
                int v = queue.poll();
                n--;
                int v1 = connected[v];
                connected[v1] ^= v;
                degree[v1]--;
                if(degree[v1] == 1) {
                    queue.add(v1);
                }
            }    
        }
        
        List<Integer> result = new ArrayList<Integer>();
        result.addAll(queue);
        return result;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-11-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 思路一:图论
  • 思路二:简化数据结构
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档