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