Участник:F.Nikitin/FindMinHeightTree

Материал из DISCOPAL
Перейти к: навигация, поиск
class Solution:
    def findMinHeightTrees(self, n, edges):
        if not edges: return [0]
 
        adjacency = collections.defaultdict(dict)
        for x, y in edges:
            adjacency[x][y], adjacency[y][x] = 1, 1
 
        while len(adjacency) > 2:
            leafs = [node for node in adjacency if len(adjacency[node]) == 1]
 
            for node in leafs:
                other = list(adjacency[node].keys())[0]
 
                del adjacency[node]
                del adjacency[other][node]
        return adjacency.keys()