루트노드를 줬으니 루트노드부터 BFS로 전위순회 하며 부모를 기록해줬다.
import sys
input =  sys.stdin.readline
from collections import deque
# BFS로 루트부터 전위순회.
def BFS(start):
    queue = deque()
    visited = [False]*(N+1)
    visited[start] = True
    queue.append(start)
    while queue:
        cur_node = queue.popleft()
        for next_node in graph[cur_node]:
            if not visited[next_node]:
                visited[next_node] = True
                super_node[next_node] = cur_node
                queue.append(next_node)
N = int(input())
graph = {i:[] for i in range(1,N+1)}
super_node = {i:0 for i in range(1,N+1)}
for _ in range(N-1):
    a,b  = map(int,input().split())
    graph[a].append(b)
    graph[b].append(a)
BFS(1)
for i in range(2,N+1):
    print(super_node[i])'practivceAlgorithm > 백준' 카테고리의 다른 글
| [백준][Python] 2629 양팔저울 (0) | 2021.07.22 | 
|---|---|
| [백준][Python] 5014 스타트링크 (0) | 2021.07.22 | 
| [백준][Python] 11723 집합 (0) | 2021.07.21 | 
| [백준][Python] 2263 트리의 순회 (0) | 2021.07.21 | 
| [백준][Python] 1759 암호만들기 (0) | 2021.07.21 |