|
| 1 | +package joshua.leetcode.bfs; |
| 2 | + |
| 3 | +import java.util.List; |
| 4 | + |
| 5 | +/** |
| 6 | + * 310. Minimum Height Trees<br/> |
| 7 | + * <p/> |
| 8 | + * <a href = "https://leetcode.com/problems/minimum-height-trees/">leetcode link</a> |
| 9 | + * <p/> |
| 10 | + * Created by joshu on 2016/5/19. |
| 11 | + */ |
| 12 | +public abstract class MinimumHeightTrees { |
| 13 | + |
| 14 | + /** |
| 15 | + * For a undirected graph with tree characteristics, we can choose any node as the root. |
| 16 | + * The result graph is then a rooted tree. |
| 17 | + * Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). |
| 18 | + * Given such a graph, write a function to find all the MHTs and return a list of their root labels. |
| 19 | + * <p/> |
| 20 | + * <b>Format</b> |
| 21 | + * <ul> |
| 22 | + * <li>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).</li> |
| 23 | + * <li>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.</li> |
| 24 | + * </ul> |
| 25 | + * <p/> |
| 26 | + * |
| 27 | + * Example 1: |
| 28 | + * <p/> |
| 29 | + * Given n = 4, edges = [[1, 0], [1, 2], [1, 3]] |
| 30 | + * <p/> |
| 31 | + * 0<br/> |
| 32 | + * |<br/> |
| 33 | + * 1<br/> |
| 34 | + * / \<br/> |
| 35 | + * 2 3<br/> |
| 36 | + * return [1] |
| 37 | + * <p/> |
| 38 | + * Example 2: |
| 39 | + * <p/> |
| 40 | + * |
| 41 | + * Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]] |
| 42 | + * <p/> |
| 43 | + * 0 1 2<br/> |
| 44 | + * \ | /<br/> |
| 45 | + * 3<br/> |
| 46 | + * |<br/> |
| 47 | + * 4<br/> |
| 48 | + * |<br/> |
| 49 | + * 5<br/> |
| 50 | + * return [3, 4] |
| 51 | + * |
| 52 | + * @param n the number of vertexes in graph |
| 53 | + * @param edges the edges in graph |
| 54 | + * @return |
| 55 | + */ |
| 56 | + public abstract List<Integer> findMinHeightTrees(int n, int[][] edges); |
| 57 | + |
| 58 | + /** |
| 59 | + * 思路来自拓扑排序。 |
| 60 | + * 这个问题先简化为假如能找到图的最长路径,那么minimum height tree的顶点就是这条路径的中间节点,如果路径长度为奇数就是1个, |
| 61 | + * 路径长度为偶数就是2个。 |
| 62 | + * 如何找到这个中间节点可以用两端出发,步长为1同时移动,相遇时的节点就是中间节点。 |
| 63 | + * 这个方法借鉴到这个问题上,从所有的叶子节点出发,每次剪去所有的叶子节点,然后更新所有其他节点的degree,直到只剩下不多于两个节点 |
| 64 | + * 迭代终止。 |
| 65 | + * <p/> |
| 66 | + * <a href="https://leetcode.com/discuss/71763/share-some-thoughts">leetcode 解答</a> |
| 67 | + * |
| 68 | + */ |
| 69 | + public static class Solution1 extends MinimumHeightTrees { |
| 70 | + |
| 71 | + @Override |
| 72 | + public List<Integer> findMinHeightTrees(int n, int[][] edges) { |
| 73 | + return null; |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments