题目地址:
https://leetcode-cn.com/probl...
题目描述:java
对于一个具备树特征的无向图,咱们可选择任何一个节点做为根。图所以能够成为树,在全部可能的树中,具备最小高度的树被称为最小高度树。给出这样的一个图,写出一个函数找到全部的最小高度树并返回他们的根节点。 格式 该图包含 n 个节点,标记为 0 到 n - 1。给定数字 n 和一个无向边 edges 列表(每个边都是一对标签)。 你能够假设没有重复的边会出如今 edges 中。因为全部的边都是无向边, [0, 1]和 [1, 0] 是相同的,所以不会同时出如今 edges 里。 示例 1: 输入: n = 4, edges = [[1, 0], [1, 2], [1, 3]] 0 | 1 / \ 2 3 输出: [1] 示例 2: 输入: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]] 0 1 2 \ | / 3 | 4 | 5 输出: [3, 4]
解答:
这一题比较有技巧,若是求任意一点到任意一点的距离,那么会时间复杂度会很大。
比较高效的作法是,每次把叶子节点从图(把树转换为图结构)删掉。
直到只剩下1个或者2个点的时候输出。c++
算法思想很简单。可是实现起来有写麻烦。若是每次都判断叶子节点,那么效率会很低。
所以使用一个数组inDegree[]表明每一个节点的入度,若入度为1就是叶子节点。
而且用一个队列(栈也能够,只要是那种能弹出的容器便可)装叶子节点。
而后宽度优先搜索队列中叶子节点,删除节点和它们对应的边,并加入新的叶子节点(有可能删除叶子节点的边以后,它的邻接点p的入度变为1,也就是inDegree[p] = 1,此时能够把p加入队列中)。
直到只剩下1个或者2个点中止。返回结果。算法
java ac代码: class Solution { public List<Integer> findMinHeightTrees(int n, int[][] edges) { List<Integer>ans = null; if(n <= 2) { ans = new ArrayList(2); for(int i = 0;i < n;i++) ans.add(i); return ans; } //去掉叶子节点,直到只剩下一个或者两个节点。 int[]inDegree = new int[n]; //用邻接表存储图。 List<Integer>[] map = new List[n]; for(int i = 0;i < n;i++) map[i] = new ArrayList(); for(int i = 0;i < edges.length;i++) { map[edges[i][0]].add(edges[i][1]); map[edges[i][1]].add(edges[i][0]); inDegree[edges[i][0]]++; inDegree[edges[i][1]]++; } int count = n; Queue<Integer>queue = new ArrayDeque(); for(int i = 0;i < n;i++) if(inDegree[i] == 1) queue.offer(i); while(count > 2) { int size = queue.size(); for(int loc = 0;loc < size;loc++) { int ii = queue.poll(); int jj = map[ii].get(0); inDegree[jj]--; if(inDegree[jj] == 1) queue.offer(jj); map[jj].remove(new Integer(ii)); map[ii].remove(new Integer(jj)); inDegree[ii] = -1; count--; } } ans = new ArrayList(queue); return ans; } }
这个和力扣(LeetCode)207很像,虽然不是拓扑排序,但都是利用一个可弹出容器装节点,而后宽度搜索容器中的节点。segmentfault