https://www.acmicpc.net/problem/2263
1부터 n까지 번호가 중복 없이 매겨진 노드로 이진 트리가 있다고 하자. 이 이진 트리의 중위 순회와 후위 순회가 주어졌을 때 전위 순회를 구하시오.
예시
이진 트리 예시. 이건 문제에서 알려주지 않음
입력
D B E A F C G
D E B F G C A
정답
A B D E C F G
실제 주어지는 이진 트리는 완전 이진 트리가 아닐 수 있음!
bt <- 주어진 이진 트리, binary tree
answer = "" # 반환할 답
def pre_order(bt):
global answer
if bt is empty or not exist: return
# 1. 루트 노드를 찾고 결과에 추가한다
# 후위 순회 결과에서 맨 마지막에 있는 노드를 찾는다. 이게 루트 노드다.
root = post-order(bt)[-1]
answer += f" {root}" # 결과에 추가
# 1. 그리고 그 왼쪽 하위 트리와 오른쪽 하위 트리를 찾는다.
# 찾은 루트 노드를 중위 순회 결과에서 찾는다.
idx = in-order(bt).index(root)
# 중위 순회 결과에서 루트 노드 왼쪽이 왼쪽 하위 트리이고
# 오른쪽이 오른쪽 하위 트리이다.
# 2. 재귀적으로 반복한다.
pre_order(bt[:idx])
pre_order(bt[idx+1 :])
print(answer)
in_order_loc = [0 for _ in range(len(in_order) + 1)]
for i, node in enumerate(in_order): in_order_loc[node] = i
def pre_order(in_st, in_end, post_st, post_end):
...
0 → in_st | 3 → idx | 6 → in_end - 1 | ||||
---|---|---|---|---|---|---|
D | B | E | A | F | C | G |
0 | 2 | 4 | 6 | |||
in_st | idx - 1 | idx + 1 | in_end - 1 |
0 → post_st | 6 → post_end - 1 | |||||
---|---|---|---|---|---|---|
D | E | B | F | G | C | A |
0 | 2 | 3 | 5 | |||
post_st | post_st + 2 | +1 | post_end - 2 |
import sys
limit_number = 10 ** 9
sys.setrecursionlimit(limit_number)
N = int(input())
in_order = tuple(map(int, sys.stdin.readline().rstrip().split()))
post_order = tuple(map(int, sys.stdin.readline().rstrip().split()))
in_order_loc = [0 for _ in range(len(in_order) + 1)]
for i, node in enumerate(in_order): in_order_loc[node] = i
answer = "" # 반환할 답
def pre_order(in_st, in_end, post_st, post_end):
global answer, N, in_order, post_order
if (in_st >= in_end) or (post_st >= post_end):
return
# 1. 루트 노드를 찾고 결과에 추가한다
# 후위 순회 결과에서 맨 마지막에 있는 노드를 찾는다. 이게 루트 노드다.
root = post_order[post_end - 1]
answer += f" {root}" # 결과에 추가
# 1. 그리고 그 왼쪽 하위 트리와 오른쪽 하위 트리를 찾는다.
# 찾은 루트 노드를 중위 순회 결과에서 찾는다.
idx = in_order_loc[root]
left_count = idx - in_st # 왼쪽 하위 트리의 갯수
# 중위 순회 결과에서 루트 노드 왼쪽이 왼쪽 하위 트리이고
# 오른쪽이 오른쪽 하위 트리이다.
# 2. 재귀적으로 반복한다.
pre_order(in_st, idx, post_st, post_st + left_count)
pre_order(idx + 1, in_end, post_st + left_count, post_end - 1)
pre_order(0, len(in_order), 0, len(post_order))
print(answer[1:])