1. 문제 설명
https://www.acmicpc.net/problem/1991
2. 아이디어
트리에 대해 아직 개념이 생소하면 어려울 수 있지만, 사실 그냥 재밌는 문제.
- 전위 순회: root -> 왼쪽 자식 -> 오른쪽 자식
- 중위 순회: 왼쪽 자식 -> root -> 오른쪽 자식
- 후위 순회: 왼쪽 자식 -> 오른쪽 자신 -> root
이 순서로 트리를 탐색하는게 끝이다.
3. 코드
import sys
input = sys.stdin.readline
tree = {}
def preorder(root):
if not root == '.':
print(root, end = '')
preorder(tree[root][0])
preorder(tree[root][1])
def inorder(root):
if not root == '.':
inorder(tree[root][0])
print(root, end = '')
inorder(tree[root][1])
def postorder(root):
if not root == '.':
postorder(tree[root][0])
postorder(tree[root][1])
print(root, end = '')
def solution():
n = int(input())
for _ in range(n):
root, left, right = input().split()
tree[root] = [left, right]
preorder('A')
print()
inorder('A')
print()
postorder('A')
solution()