📖문제
https://www.acmicpc.net/problem/11725
bfs를 사용했다😊
import sys
from collections import deque
n=int(sys.stdin.readline().rstrip())
graph=[[] for i in range(n+1)]
#각 노드가 연결된 정보를 저장
# ex) graph=[[], [6, 4], [4], [6, 5], [1, 2, 7], [3], [1, 3], [4]]
for _ in range(n-1):
a,b=map(int,sys.stdin.readline().split())
graph[a].append(b)
graph[b].append(a)
# 각 노드가 방문된 정보를 저장할 리스트
visited=[False]*(n+1)
answer=[]
#BFS
def bfs(graph,start,visited):
#시작 노드 큐에 넣기
queue=deque([start])
visited[start]=True
while queue:
#큐의 가장 처음 노드를 빼고
v=queue.popleft()
#그 노드에 연결된 노드들 중 방문하지 않은 것을 큐에 넣는다
for i in graph[v]:
if not visited[i]:
queue.append(i)
answer.append((v,i))
#방문표시
visited[i]=True
bfs(graph,1,visited)
answer=sorted(answer, key=lambda x: x[1])
for i in range(len(answer)):
print(answer[i][0])