목차

트리의 순회

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()