ps | |
---|---|
링크 | acmicpc.net/… |
출처 | BOJ |
문제 번호 | 2263 |
문제명 | 트리의 순회 |
레벨 | 골드 3 |
분류 |
트리, 분할정복 |
시간복잡도 | O(n) |
인풋사이즈 | n<=100000 |
사용한 언어 | Python |
제출기록 | 328ms |
최고기록 | 224ms |
해결날짜 | 2020/11/20 |
"""Solution code for "BOJ 2263. 트리의 순회".
- Problem link: https://www.acmicpc.net/problem/2263
- Solution link: http://www.teferi.net/ps/problems/boj/2263
"""
import sys
def solve(n, inorder, postorder, idx_by_num):
def solve_rec(inorder_beg, postorder_beg, size):
root = postorder[postorder_beg + size - 1]
print(root, end=' ')
left_tree_size = idx_by_num[root] - inorder_beg
if left_tree_size > 0:
solve_rec(inorder_beg, postorder_beg, left_tree_size)
if (right_tree_size := size - left_tree_size - 1) > 0:
solve_rec(inorder_beg + left_tree_size + 1,
postorder_beg + left_tree_size,
right_tree_size)
solve_rec(0, 0, n)
def main():
sys.setrecursionlimit(10**9)
n = int(input())
inorder = [int(x) for x in input().split()]
postorder = [int(x) for x in input().split()]
idx_by_num = [0] * (n + 1)
for idx, num in enumerate(inorder):
idx_by_num[num] = idx
solve(n, inorder, postorder, idx_by_num)
if __name__ == '__main__':
main()