코드 출처 @kkamisister
N = int(input())
tree = {}
for _ in range(N):
root, left, right = input().split()
tree[root] = [left, right]
# 전위 순회
def preorder(root):
if root != '.':
print(root, end='')
preorder(tree[root][0])
preorder(tree[root][1])
# 중위 순회
def inorder(root):
if root != '.':
inorder(tree[root][0])
print(root, end='')
inorder(tree[root][1])
# 후위 순회
def postorder(root):
if root != '.':
postorder(tree[root][0])
postorder(tree[root][1])
print(root, end='')
preorder('A')
print()
inorder('A')
print()
postorder('A')
오늘 코드 리뷰하다 삽질했다는 것을 깨달았다.. 문자열도 비교연산자 사용이 가능하다는 점.
Python 문자열 비교 방법
아스키 코드 기준 비교 (대문자 65 - 90 // 소문자 97 - 122 의 코드 번호)
A < B < C ... < X < Y< Z < a < b < ...< z
ord() - 알파벳을 입력 받아 아스키 코드로 변환
chr() - 정수를 입력 받아 아스키 코드 문자로 변환
이걸 몰라 dictionary에 다 때려박던 날들이여 안녕~
import sys
input = sys.stdin.readline
def alpha_to_decimal(a):
if a == ".":
return 0
else:
return ord(a) - 64
def preorder(idx):
print(chr(idx+64), end="")
if left[idx]:
preorder(left[idx])
if right[idx]:
preorder(right[idx])
return
def inorder(idx):
if left[idx]:
inorder(left[idx])
print(chr(idx + 64), end="")
if right[idx]:
inorder(right[idx])
return
def postorder(idx):
if left[idx]:
postorder(left[idx])
if right[idx]:
postorder(right[idx])
print(chr(idx + 64), end="")
return
N = int(input())
left = [0] * 27
right = [0] * 27
for i in range(N):
par, lc, rc = map(alpha_to_decimal, input().strip().split())
left[par] = lc
right[par] = rc
preorder(1)
print()
inorder(1)
print()
postorder(1)
print()
영광굴비