[leetcode] 310.Minimum Height Trees

£神魔★判官ぃ 2022-09-24 07:30 204阅读 0赞

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.

题目链接:310.Minimum Height Trees

这是一道谷歌公司的题目。我个人觉得这道题目是很具有代表性的。同时也是很难做的。

这道题有许多不同的思路。从这道题的discussion中就可以到许多令人惊艳的想法和思路。我将其总结如下。大致有两种思路。深入的理解和应用这两种思路对提高编程水平是大有裨益的。

首先这道题目要考虑到的是,对于一颗给定的树,我们要寻找的最小高度树(MHT)可能有几种呢?答案是一种或两种。这个结论可以用反证法予以证明。
假设给定一棵树,我们可以找到三种不同根结点的MHT。不失普遍性的情况下,我们可以假设这三个根结点是两两相连接的,记为r1,r2和r3。假设这三者作为根结点所构成的树的高度均为h。那么r1到r3的最大距离为2(或更大,如果这三个结点不是两两相邻的话)。那么r1作为根结点所构成的MHT的高度实际上为h+2(因为r3高为h,而r1距离r3为2以上)。那么r1构成的树就不是MHT,这与我们的假设矛盾。

基于以上的结论。我们知道了实际上我们需要在给定的树中找打1个或2个结点来作为MHT的根结点。

方法1:

若我们由特殊到一般地考虑这道题目,我们首先考虑一个没有任何分支的树,既所谓的路径图(path graph,如1-2-3-4-5)。对于一个有n个结点的路径图,寻找MHT非常简单,只要找到其中间结点即可。假设我们不知道n,也不能任意访问某位置上的结点,那么使用双指针的方法可以方便地寻找其中间结点使用两个指针分别指向该路径图的两端并使它们以相同的速度移动。当它们相遇或者相距一个单位的时候,我们就找到了需要的根结点。

那么对于一颗有分支的树,我们可以使用指针指向所有的叶子结点,然后让这些指针以相同的速度移动,当两个指针相遇的时候,保留一个,然后使其继续移动。只到最后两个指针相遇或者相距一个单位的时候。它们所指的结点即为根结点。
具体实现的时候,我们可以用类似于广度优先拓扑搜索的思路,去掉树的所有叶子结点,更新每个结点的度,然后再去掉所有新产生的叶子结点,只到剩下一个或两个结点为止。
注意对于N个结点的书我们总是有N-1条边。
Java代码如下:
时间和空间复杂度均为O(n)

  1. public List<Integer> findMinHeightTrees(int n, int[][] edges) {
  2. /*
  3. find out the leaves in every loop and delete the leaves from the tree. Stop when there is only 1 or 2 nodes left.
  4. Since the MHT's root is always at the middle point of the tree, there can at most be 2 different roots for a MHT.
  5. */
  6. if (n == 1) {
  7. return Collections.singletonList(0);
  8. }
  9. //Use a list of hashset to store the adjacent nodes of every nodes in the tree based on the edges passed in to this program.
  10. List<Set<Integer>> treeadj = new ArrayList<>(n);
  11. for (int i = 0; i < n; i++) {
  12. treeadj.add(new HashSet<>());
  13. }
  14. // The following loop can also be wrote as following which is more efficient
  15. // for (int[] edge : edges) {
  16. // treeadj.get(edge[0]).add(edge[1]);
  17. // treeadj.get(edge[1]).add(edge[0]);
  18. // }
  19. for (int i = 0; i < edges.length; i++) {
  20. treeadj.get(edges[i][0]).add(edges[i][1]);
  21. treeadj.get(edges[i][1]).add(edges[i][0]);
  22. }
  23. //Use a List leaves to store the leaves of the tree
  24. //This is the initiation of the leaves List
  25. List<Integer> leaves = new ArrayList<>();
  26. for (int i = 0; i < n; i++) {
  27. if (treeadj.get(i).size() == 1) {
  28. leaves.add(i);
  29. }
  30. }
  31. while (n > 2) {
  32. n -= leaves.size();
  33. //Ust new leaves to store the newly generated leaves becasue of deleting the old leaves from the tree
  34. List<Integer> newLeaves = new ArrayList<>();
  35. for (int i = 0; i < leaves.size(); i++) {
  36. int j = treeadj.get(leaves.get(i)).iterator().next();
  37. treeadj.get(j).remove(leaves.get(i));
  38. if (treeadj.get(j).size() == 1) {
  39. newLeaves.add(j);
  40. }
  41. }
  42. leaves = newLeaves;
  43. }
  44. return leaves;
  45. }

方法2:

上面我们已经说明了构成MHT的根结点一定在一棵树距离最远的两个结点构成的路径的中间一个或两个位置。那么我们需要寻找一棵树的最大长度的两个结点的中点。寻找最大长度的方法有两种,一种是树的动态规划(Tree DP),一种是做两次树遍历(BFS或DFS遍历)。下面分别讨论。

  • 做两次树遍历
    首先任意选取树的一个结点x作为遍历开始的根结点,然后利用BFS或DFS找到距离x最远的结点y。y一定位于某一条最大距离的一端。然后以y作为遍历开始的根结点,执行另一次BFS或DFS,找到距离y最远的结点z。那么从y到z的所构成的最远路径的中点就是我们需要寻找的MHT的根。
    Java代码如下:
    时间复杂度和空间复杂度均为O(n)。

    public List findMinHeightTrees(int n, int[][] edges) {

    1. /*
    2. Randomly select a node x as the root, do a dfs/bfs to find the node y that has the longest distance from x.
    3. Then y must be one of the endpoints on some longest path.
    4. Let y the new root, and do another dfs/bfs. Find the node z that has the longest distance from y.
    5. Now, the path from y to z is the longest one, and thus its middle point(s) is the answer.
    6. */
    7. if (n <= 0) {
    8. return new ArrayList<>();
    9. }
    10. List<Integer>[] treeAdj = new List[n];
    11. for (int i = 0; i < n; i++) {
    12. treeAdj[i] = new ArrayList<>();
    13. }
    14. for (int[] edge : edges) {
    15. treeAdj[edge[0]].add(edge[1]);
    16. treeAdj[edge[1]].add(edge[0]);
    17. }
    18. int[] dist1 = new int[n];
    19. int[] dist2 = new int[n];
    20. int[] parent = new int[n];
    21. bfs(0, treeAdj, dist1, parent, n);
    22. int root = 0;
    23. for (int i = 0; i < n; i++) {
    24. if (dist1[i] > dist1[root]) {
    25. root = i;
    26. }
    27. }
    28. bfs(root, treeAdj, dist2, parent, n);
    29. root = 0;
    30. for (int i = 0; i < n; i++) {
    31. if (dist2[i] > dist2[root]) {
    32. root = i;
    33. }
    34. }
    35. List<Integer> list = new ArrayList<>();
    36. while (root != -1) {
    37. list.add(root);
    38. root = parent[root];
    39. }
    40. if (list.size() % 2 == 1) return Arrays.asList(list.get(list.size() / 2));
    41. else return Arrays.asList(list.get(list.size() / 2 - 1), list.get(list.size() / 2));

    }

    private void bfs(int start, List[] adj, int[] dist, int[] parent, int n) {

    1. Queue<Integer> queue = new ArrayDeque<>();
    2. boolean[] visited = new boolean[n];
    3. queue.add(start);
    4. dist[start] = 0;
    5. visited[start] = true;
    6. parent[start] = -1;
    7. while (!queue.isEmpty()) {
    8. int u = queue.poll();
    9. for (int v : adj[u]) {
    10. if (!visited[v]) {
    11. visited[v] = true;
    12. dist[v] = dist[u] + 1;
    13. parent[v] = u;
    14. queue.add(v);
    15. }
    16. }
    17. }

    }

  • 动态规划
    利用数组dp[i]储存以i作为根结点时的树的高度。利用DFS和动态规划的思路来计算dp[0]dp[n-1]
    任意选取一个结点作为根结点开始DFS,例如0。
    当我们到达一个结点u的时候,利用T来表示去掉u的子树后余下的树。利用height[]来表示u的高度,使用变量acc记录去掉u的子树后树T中以u作为结束结点的最长路径的长度(既u的深度)。那么显然dp[u] = max{acc, height[u]}。acc对于根结点来说是0。

    | |

    1. . .
    2. /|\ /|\
    3. * u * * u *
    4. /|\
    5. / | \
    6. * v *

.表示单独结点,*表示子树。
那么接下来我们需要考虑u的子结点,用v表示。那么v结点的acc显然等于下面两种情况中的最大值

  1. acc+1 直接将u点的acc长度向uv延伸1
  2. max(height[v’]+2) v’是u的子结点且v’ != v。如下图所示

    u

    1. /|
    2. / |
    3. v' v
    4. |
    5. .
    6. .
    7. .
    8. |
    9. .

情况2看似需要O(k)时间(k为结点u的度),然而实际上我们只需要O(1)时间来处理情况2。方法是我们为每个结点保留其最大高度(height1[])和第二大高度(height2[])两个量(也就是将最大高度的分支去掉后该结点的最大高度)。那么情况2,max{height[v’] + 2}就是: I. height1[u] + 1(当v不在u的最大高度所在的路径上时,也就是height1[u] != height1[v] + 1时),或 II. height2[u] + 1(当v在u的最大高度所在的路径上时,也就是height1[u] == height1[v] + 1时)。
那么经过DFS,所有的节点的最大高度(dp[])都被计算出来之后,我们只需找到高度最小的结点返回即可。
Java代码如下:
时间和空间复杂度均为O(n)。

  1. public List<Integer> findMinHeightTrees(int n, int[][] edges) {
  2. /**
  3. * LeetCode 310 - Minimum Height Trees
  4. *
  5. * Alternatively, one can solve this problem directly by tree dp.
  6. * Let dp[i] be the height of the tree when the tree root is i.
  7. * We compute dp[0] ... dp[n - 1] by tree dp in a dfs manner.
  8. *
  9. * Arbitrarily pick a node, say node 0, as the root, and do a dfs.
  10. * When reach a node u, and let T be the subtree by removing all u's descendant (see the right figure below).
  11. * We maintain a variable acc that keeps track of the length of the longest path in T with one endpoint being u.
  12. * Then dp[u] = max(height[u], acc)
  13. * Note, acc is 0 for the root of the tree.
  14. *
  15. * | |
  16. * . .
  17. * /|\ /|\
  18. * * u * * u *
  19. * /|\
  20. * / | \
  21. * * v *
  22. *
  23. * . denotes a single node, and * denotes a subtree (possibly empty).
  24. *
  25. * Now it remains to calculate the new acc for any of u's child, v.
  26. * It is easy to see that the new acc is the max of the following
  27. *
  28. * 1) acc + 1 --- extend the previous path by the edge uv;
  29. * 2) max(height[v'] + 2), where v != v' --- see below for an example.
  30. *
  31. * u
  32. * /|
  33. * / |
  34. * v' v
  35. * |
  36. * .
  37. * .
  38. * .
  39. * |
  40. * .
  41. *
  42. * In fact, the second case can be computed in O(1) time instead of spending a time proportional to the degree of u.
  43. * Otherwise, the runtime can be quadratic when the degree of some node is Omega(n).
  44. * The trick here is to maintain two heights of each node, the largest height (the conventional height), and the second largest height
  45. * (the height of the node after removing the branch w.r.t. the largest height).
  46. *
  47. * Therefore, after the dfs, all dp[i]'s are computed, and the problem can be answered trivially.
  48. * The total runtime is still O(n).
  49. */
  50. if (n <= 0) return new ArrayList<>();
  51. if (n == 1) return Arrays.asList(0);
  52. int[] height1 = new int[n]; //stores the largest height of a node
  53. int[] height2 = new int[n]; //stores the second largest height of a node
  54. int[] dp = new int[n];
  55. List<Integer>[] tree = new List[n];
  56. for (int i = 0; i < n; i++) {
  57. tree[i] = new ArrayList<>();
  58. }
  59. for (int[] edge : edges) {
  60. tree[edge[0]].add(edge[1]);
  61. tree[edge[1]].add(edge[0]);
  62. }
  63. dfs(0, -1, height1, height2, tree);
  64. dfs(0, -1, 0, height1, height2, dp, tree);
  65. int min = dp[0];
  66. for (int i = 0; i < n; i++) {
  67. if (dp[i] < min) {
  68. min = dp[i];
  69. }
  70. }
  71. List<Integer> result = new ArrayList<>();
  72. for (int i = 0; i < n; i++) {
  73. if (dp[i] == min) {
  74. result.add(i);
  75. }
  76. }
  77. return result;
  78. }
  79. private void dfs(int node, int parent, int[] height1, int[] height2, List<Integer>[] tree) {
  80. height1[node] = Integer.MIN_VALUE;
  81. height2[node] = Integer.MIN_VALUE;
  82. for (int child : tree[node]) {
  83. if (child != parent) {
  84. dfs(child, node, height1, height2, tree);
  85. int tmpheight = height1[child] + 1;
  86. if (tmpheight > height1[node]) {
  87. height2[node] = height1[node];
  88. height1[node] = tmpheight;
  89. }
  90. else if(tmpheight > height2[node]) {
  91. height2[node] = tmpheight;
  92. }
  93. }
  94. }
  95. height1[node] = Math.max(height1[node], 0);
  96. }
  97. private void dfs(int node, int parent, int acc, int[] height1, int[] height2, int[] dp, List<Integer>[] tree) {
  98. dp[node] = Math.max(acc, height1[node]);
  99. for (int child : tree[node]) {
  100. if (child != parent) {
  101. int newAcc = Math.max(acc + 1, height1[child] + 1 == height1[node] ? height2[node] + 1 : height1[node] + 1);
  102. dfs(child, node, newAcc, height1, height2, dp, tree);
  103. }
  104. }
  105. }

写完这道题的三种代码。感觉身体被掏空。。。。

这里写图片描述

发表评论

表情:
评论列表 (有 0 条评论,204人围观)

还没有评论,来说两句吧...

相关阅读