본문 바로가기

코딩테스트 준비

전위 순회, 중위 순회, 후위 순회

import sys
n = int(input())
graph = {}
for i in range(n):
x, y, z = sys.stdin.readline().split()
graph[x] = (y, z)
def preorder(root):
print(root, end='')
for a in graph[root]:
if a != '.':
preorder(a)
def inorder(root):
if graph[root][0] != '.':
inorder(graph[root][0])
print(root, end='')
if graph[root][1] != '.':
inorder(graph[root][1])
def postorder(root):
for a in graph[root]:
if a != '.':
postorder(a)
print(root, end='')
preorder('A')
print()
inorder('A')
print()
postorder('A')

전위 순회는 뿌리->왼쪽 자식->오른쪽 자식 순

중위 순회는 왼쪽자식-> 뿌리-> 오른쪽 자식

후위 순회는 왼쪽자식->오른쪽 자식-> 뿌리