Skip to content

Instantly share code, notes, and snippets.

@maehrm
Created January 17, 2026 08:56
Show Gist options
  • Select an option

  • Save maehrm/c59616e84ecf56829f6a874a55bcb5be to your computer and use it in GitHub Desktop.

Select an option

Save maehrm/c59616e84ecf56829f6a874a55bcb5be to your computer and use it in GitHub Desktop.
import sys
sys.setrecursionlimit(10**9)
def dfs(v, visited, ans):
visited[v] = True
ans.append(v + 1)
for u in G[v]:
if visited[u]:
continue
dfs(u, visited, ans)
ans.append(v + 1)
return
N = int(input())
G = [[] for _ in range(N)]
for _ in range(N - 1):
a, b = map(lambda x: int(x) - 1, input().split())
G[a].append(b)
G[b].append(a)
for i in range(N): # 最初、ここがなくてWAが出た。
G[i].sort()
ans = []
dfs(0, [False] * N, ans)
print(*ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment