주어진 트리를 전위순회, 중위순회, 후위순회를 하는 프로그램을 작성해야한다.
n = int(input())
graph = []
for _ in range(n):
graph.append(list(map(str, input().split())))
ans = [[], [], []]
def pre(node):
for x in graph:
if x[0] == node and x[1] == '.' and x[2] == '.':
ans[0].append(node)
return
if x[0] == node:
ans[0].append(node)
pre(x[1])
pre(x[2])
def inorder(node):
for x in graph:
if x[0] == node and x[1] == '.' and x[2] == '.':
ans[1].append(node)
return
if x[0] == node and x[1] != '.':
inorder(x[1])
ans[1].append(node)
inorder(x[2])
if x[0] == node and x[1] == '.':
ans[1].append(node)
inorder(x[2])
def post(node):
for x in graph:
if x[0] == node and x[1] == '.' and x[2] == '.':
ans[2].append(node)
return
if x[0] == node and x[1] != '.':
post(x[1])
post(x[2])
ans[2].append(node)
if x[0] == node and x[1] == '.':
post(x[2])
ans[2].append(node)
pre('A')
inorder('A')
post('A')
for x in ans:
print(''.join(x))
우선 통과는 했지만 풀이를 하면서 코드가 장황하고 지저분하다는 생각이 들었다.
import sys
N = int(sys.stdin.readline().strip())
tree = {}
for n in range(N):
root, left, right = sys.stdin.readline().strip().split()
tree[root] = [left, right]
def preorder(root):
if root != '.':
print(root, end='') # root
preorder(tree[root][0]) # left
preorder(tree[root][1]) # right
def inorder(root):
if root != '.':
inorder(tree[root][0]) # left
print(root, end='') # root
inorder(tree[root][1]) # right
def postorder(root):
if root != '.':
postorder(tree[root][0]) # left
postorder(tree[root][1]) # right
print(root, end='') # root
preorder('A')
print()
inorder('A')
print()
postorder('A')