1991: 트리 순회

ewillwin·2023년 6월 14일
0

Problem Solving (BOJ)

목록 보기
64/230

import sys
from collections import deque

N = int(input())
tree = {}

for n in range(N):
	root, left, right = sys.stdin.readline().strip().split()
	tree[root] = [left, right]

def preorder(root): #root -> left -> right
	if root != '.':
		print(root, end = '')
		preorder(tree[root][0])
		preorder(tree[root][1])

def inorder(root): #left -> root -> right
	if root != '.':
		inorder(tree[root][0])
		print(root, end = '')
		inorder(tree[root][1])

def postorder(root): #left -> right -> root
	if root != '.':
		postorder(tree[root][0])
		postorder(tree[root][1])
		print(root, end = '')

preorder('A')
print()
inorder('A')
print()
postorder('A')
print()
  • 재귀로 구현
  • 전위 순회 (preorder): root -> left -> right 순서
  • 중위 순회 (inorder): left -> root -> right 순서
  • 후위 순회 (postorder): left -> right -> root 순서
profile
💼 Software Engineer @ LG Electronics | 🎓 SungKyunKwan Univ. CSE

0개의 댓글