動機

  1. 第一次看到bfs這麼用
  2. 這樣叫topo sort嗎?
  3. 很漂亮的算法,真的很漂亮

Problem

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.

Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h))  are called minimum height trees (MHTs).

Return a list of all MHTs' root labels. You can return the answer in any order.

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

 

Example 1:

Input: n = 4, edges = [[1,0],[1,2],[1,3]]Output: [1]Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.

Example 2:

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

Example 3:

Input: n = 1, edges = []Output: [0]

Example 4:

Input: n = 2, edges = [[0,1]]Output: [0,1]

 

Constraints:

  • 1 <= n <= 2 * 104
  • edges.length == n - 1
  • 0 <= ai, bi < n
  • ai != bi
  • All the pairs (ai, bi) are distinct.
  • The given input is guaranteed to be a tree and there will be no repeated edges.

Sol

觀察會發現,其實我們要找的點都在中點上!!

所以問題就是怎麼找中點

不像linked list有起點終點,但我們有leaf

這有點像two pointer,從兩邊去逼近,一直把leaf拿掉,直到剩下兩個以下的node

要注意的是要用圈為單位,不能用node為單位,不然就會在還有leaf的狀態,因為兩個以下的node而退除loop

class Solution:
    def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
        if n <= 2:
            return list(range(n))
        else:
            gh = defaultdict(set)

            for (a,b) in edges:
                gh[a].add(b)
                gh[b].add(a)

            q = deque([[k for (k,v) in gh.items() if len(v) == 1]])
            while len(gh) > 2:
                rs = q.popleft()
                leafs = []
                for r in rs:
                    for x in gh[r]: # should be only one, but we cant use index on set
                        gh[x].remove(r)
                        if len(gh[x]) == 1:
                            leafs.append(x)
                    del gh[r]
                q.append(leafs)
            return list(gh.keys())