Published:
Updated:


Solution

import collections
from typing import List


class Solution:
    # μ™Έκ³½ λ…Έλ“œ -> ν•œ 개의 μ΄μ›ƒλ§Œ κ°€μ§€λŠ” λ…Έλ“œ, 트리의 높이λ₯Ό μ΅œμ†Œν™”ν•˜λŠ” λ…Έλ“œλ“€ 쀑 ν•˜λ‚˜μΌ 수 있음
    # BFS둜 탐색 -> μ‹œμž‘ λ…Έλ“œλΆ€ν„° μ‹œμž‘ν•˜μ—¬ μΈμ ‘ν•œ λ…Έλ“œλ₯Ό 큐에 μΆ”κ°€ν•˜κ³ , νμ—μ„œ λ…Έλ“œλ₯Ό ν•˜λ‚˜μ”© κΊΌλ‚΄μ–΄ 탐색
    # μ΅œμ†Œ 높이 탐색 방법 -> μ™Έκ³½ λ…Έλ“œλ‘œλΆ€ν„° μ§„ν–‰ν•˜λ©΄μ„œ λ…Έλ“œλ“€μ„ 탐색, λͺ¨λ“  μ™Έκ³½ λ…Έλ“œκ°€ νμ—μ„œ 제거될 λ•ŒκΉŒμ§€ 반볡
    def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
        # κ·Έλž˜ν”„μ— λ…Έλ“œκ°€ ν•˜λ‚˜λ§Œ μžˆλŠ” 경우
        if n == 1:
            return [0]

        graph = collections.defaultdict(set)

        # 인접 리슀트(graph) 생성
        for x, y in edges:
            graph[x].add(y)
            graph[y].add(x)

        # μ™Έκ³½ λ…Έλ“œ(outsides) κ΅¬ν•˜κΈ°
        outsides = []
        for node in graph:
            if len(graph[node]) == 1:
                outsides.append(node)

        while n > 2:  # λ…Έλ“œκ°€ 2 μ΄ν•˜κ°€ 될 λ•Œ 쀑단
            # ν˜„μž¬ μ™Έκ³½ λ…Έλ“œμ˜ 수λ₯Ό 빼쀌으둜써 λ…Έλ“œμ˜ 수 μ—…λ°μ΄νŠΈ
            n -= len(outsides)

            # λ‹€μŒ λ‹¨κ³„μ˜ μ™Έκ³½ λ…Έλ“œλ₯Ό λ‹΄λŠ” 리슀트
            new_outsides = []

            for outside in outsides:
                # ν˜„μž¬ μ™Έκ³½ λ…Έλ“œμ˜ 이웃 λ…Έλ“œ
                # pop(): 이웃 λ…Έλ“œ 쀑 ν•˜λ‚˜λ₯Ό 선택 ν›„ -> κ·Έ λ…Έλ“œλ₯Ό μ΄μ™Έμ˜ μ΄μ›ƒλ“€κ³Όμ˜ 연결을 끊음
                outside_neighbor = graph[outside].pop()

                # 이웃 λ…Έλ“œμ™€μ˜ 연결을 λŠμ–΄μ€Œ -> 이λ₯Ό 톡해 μ™Έκ³½ λ…Έλ“œμ™€ μ—°κ²°λœ 게 제거됨
                graph[outside_neighbor].remove(outside)

                # μ™Έκ³½ λ…Έλ“œμΈ 경우
                if len(graph[outside_neighbor]) == 1:
                    # λ‹€μŒ λ‹¨κ³„μ˜ μ™Έκ³½ λ…Έλ“œμ— λ‹΄μŒ
                    new_outsides.append(outside_neighbor)

                outsides = new_outsides

        return outsides

Leave a comment