내 풀이
N = int(input())
tree = {}
for _ in range(N):
key, left, right = input().split()
tree[key] = (left, right)
def preorder(key, tree):
print(key ,end='')
if tree[key][0] != '.':
preorder(tree[key][0], tree)
if tree[key][1] != '.':
preorder(tree[key][1], tree)
def inorder(key, tree):
if tree[key][0] != '.':
inorder(tree[key][0], tree)
print(key ,end='')
if tree[key][1] != '.':
inorder(tree[key][1], tree)
def postorder(key, tree):
if tree[key][0] != '.':
postorder(tree[key][0], tree)
if tree[key][1] != '.':
postorder(tree[key][1], tree)
print(key ,end='')
preorder('A', tree)
print()
inorder('A', tree)
print()
postorder('A', tree)
클래스 버전
class Node:
def __init__(self, item, left, right):
self.item = item
self.left = left
self.right = right
def preorder(node): # 전위 순회
print(node.item, end='')
if node.left != '.':
preorder(tree[node.left])
if node.right != '.':
preorder(tree[node.right])
def inorder(node): # 중위 순회
if node.left != '.':
inorder(tree[node.left])
print(node.item, end='')
if node.right != '.':
inorder(tree[node.right])
def postorder(node): # 후위 순회
if node.left != '.':
postorder(tree[node.left])
if node.right != '.':
postorder(tree[node.right])
print(node.item, end='')
if __name__ == "__main__":
N = int(input())
tree = {}
for _ in range(N):
node, left, right = map(str, input().split())
tree[node] = Node(node, left, right)
# print(tree)
preorder(tree['A'])
print()
inorder(tree['A'])
print()
postorder(tree['A'])