[Leetcode] 310. Minimum Height Trees


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.
Solution
from collections import deque
class Solution:
    def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
        ans=[]
        cnt=n #to track the left number of nodes(not visited)
        inDegrees=[0]*n #inDegree means number of connected node except for visited node
        graph=[[] for _ in range(n)]
        
        if n<=2:
            return [i for i in range(n)]
        
        
        for a,b in edges:
            graph[a].append(b)
            graph[b].append(a)
            inDegrees[a]+=1
            inDegrees[b]+=1

        lst= deque([i for i in range(n) if inDegrees[i]==1])
        #make first deque with leaf nodes.
        
        while lst:
            l=len(lst)
            cnt-=l
            if cnt<=2: #the number of answer root node is only 1 or 2.
                break
            
            for _ in range(l):#like BFS searching.
                cur=lst.popleft()
                for nxt in graph[cur]:
                    if inDegrees[nxt]==1:
                        continue
                    
                    inDegrees[nxt]-=1
                    if inDegrees[nxt]==1:
                        lst.append(nxt)

	#finding out root node
        for i,v in enumerate(inDegrees):
            if v!=1:
                ans.append(i)
                cnt-=1
                if cnt==0:
                    break
        
            
        return ans
最初は頭がつかめず、テーマを見て、初めてトポロジーソートを発見しました.この問題を解決する前に、GeeksForGeeksでトポロジーソートを学習する必要があります.
トポロジーソートにはDFSモードKahn'sアルゴリズムの2種類があります.みんな知っていればよかったのに.
解題過程は下図からinsightを得ることができる.(なぜ画像サイズを調整できないのか)
特に私が使っている方法はInDegreeのKahn'sアルゴリズムを使っています.実はGeeks ForGeeksを見ても考えられないそこで,ディスカッション投稿では,次の行を読み,いくつかのヒントを得て解答を行った.
We are basically trying to delete all leaf nodes at every step. This is very similar to Kahn's Algo or sometimes known as BFS Topological Sort. ( ref )
これについて以下のように解釈する.私たちが探しているノードは、最小の高さを持つルートノードです.したがって、inDegreeが1のノードであるleafノードを削除し、ルートノードに近づくことができる.
またleetcode自体のヒントも役立ちます.
How many MHTs can a graph have at most?
表示できるルートノードは1つではなく2つであることがわかります.