https://www.acmicpc.net/problem/5639
- 그래프 이론
- 그래프 탐색
- 트리
- 재귀
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
def pre_to_post(start, end):
if start > end:
return
root = preorder[start]
# root보다 커지는 인덱스 찾기
idx = start
while idx <= end:
if preorder[idx] > root:
break
idx += 1
# 왼쪽
pre_to_post(start+1, idx-1)
# 오른쪽
pre_to_post(idx, end)
# 루트
print(root)
# 입력
preorder = []
while True:
try:
preorder.append(int(input()))
except:
# EOF -> break
break
# pre_to_post
pre_to_post(0, len(preorder)-1)
# 입력
preorder = []
while True:
try:
preorder.append(int(input()))
except:
# EOF -> break
break
def pre_to_post(start, end):
if start > end:
return
root = preorder[start]
# root보다 커지는 인덱스 찾기
idx = start
while idx <= end:
if preorder[idx] > root:
break
idx += 1
# 왼쪽
pre_to_post(start+1, idx-1)
# 오른쪽
pre_to_post(idx, end)
# 루트
print(root)
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
def pre_to_post(preorder):
global postorder
if len(preorder) == 0:
return
root = preorder[0]
left = []
right = []
for i in range(1, len(preorder)):
if preorder[i] < root:
left.append(preorder[i])
else:
right.append(preorder[i])
pre_to_post(left)
pre_to_post(right)
postorder.append(root)
postorder = []
preorder = []
while True:
try:
preorder.append(int(input()))
except:
break
pre_to_post(preorder)
for x in postorder:
print(x)