1. 程式人生 > >[LeetCode] Minimum Height Trees 最小高度樹

[LeetCode] Minimum Height Trees 最小高度樹

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

.

Example 1:

Given n = 4edges = [[1, 0], [1, 2], [1, 3]]

        0
        |
        1
       / \
      2   3

return [1]

Example 2:

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

     0  1  2
      \ | /
        3
        |
        4
        |
        5

return [3, 4]

Hint:

  1. How many MHTs can a graph have at most?

Note:

(1) 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.”

(2) The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

Credits:
Special thanks to @peisi for adding this problem and creating all test cases.

Update (2015-11-25):
The function signature had been updated to return List<Integer> instead of integer[]. Please click the reload button above the code editor to reload the newest default code definition.

這道題雖然是樹的題目,但是跟其最接近的題目是Course Schedule 課程清單Course Schedule II 課程清單之二。由於LeetCode中的樹的題目主要都是針對於二叉樹的,而這道題雖說是樹但其實本質是想考察圖的知識,這道題剛開始在拿到的時候,我最先想到的解法是遍歷的點,以每個點都當做根節點,算出高度,然後找出最小的,但是一時半會又寫不出程式來,於是上網看看大家的解法,發現大家推崇的方法是一個類似剝洋蔥的方法,就是一層一層的褪去葉節點,最後剩下的一個或兩個節點就是我們要求的最小高度樹的根節點,這種思路非常的巧妙,而且實現起來也不難,跟之前那到課程清單的題一樣,我們需要建立一個圖g,是一個二維陣列,其中g[i]是一個一維陣列,儲存了i節點可以到達的所有節點。我們開始將所有隻有一個連線邊的節點(葉節點)都存入到一個佇列queue中,然後我們遍歷每一個葉節點,通過圖來找到和其相連的節點,並且在其相連節點的集合中將該葉節點刪去,如果刪完後此節點也也變成一個葉節點了,加入佇列中,再下一輪刪除。那麼我們刪到什麼時候呢,當節點數小於等於2時候停止,此時剩下的一個或兩個節點就是我們要求的最小高度樹的根節點啦,參見程式碼如下:

C++ 解法一:

class Solution {
public:
    vector<int> findMinHeightTrees(int n, vector<pair<int, int> >& edges) {
        if (n == 1) return {0};
        vector<int> res;
        vector<unordered_set<int>> adj(n);
        queue<int> q;
        for (auto edge : edges) {
            adj[edge.first].insert(edge.second);
            adj[edge.second].insert(edge.first);
        }
        for (int i = 0; i < n; ++i) {
            if (adj[i].size() == 1) q.push(i);
        }
        while (n > 2) {
            int size = q.size();
            n -= size;
            for (int i = 0; i < size; ++i) {
                int t = q.front(); q.pop();
                for (auto a : adj[t]) {
                    adj[a].erase(t);
                    if (adj[a].size() == 1) q.push(a);
                }
            }
        }
        while (!q.empty()) {
            res.push_back(q.front()); q.pop();
        }
        return res;
    }
};

Java 解法一:

public class Solution {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        if (n == 1) return Collections.singletonList(0);
        List<Integer> leaves = new ArrayList<>();
        List<Set<Integer>> adj = new ArrayList<>(n);
        for (int i = 0; i < n; ++i) adj.add(new HashSet<>());
        for (int[] edge : edges) {
            adj.get(edge[0]).add(edge[1]);
            adj.get(edge[1]).add(edge[0]);
        }
        for (int i = 0; i < n; ++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 t = adj.get(i).iterator().next();
                adj.get(t).remove(i);
                if (adj.get(t).size() == 1) newLeaves.add(t);
            }
            leaves = newLeaves;
        }
        return leaves;
    }
}

此題還有遞迴的解法(未完待續...)

類似題目:

參考資料: