목차

트리

ps
링크acmicpc.net/…
출처BOJ
문제 번호4256
문제명트리
레벨골드 3
분류

분할정복

시간복잡도O(n)
인풋사이즈n<=1000
사용한 언어Python
제출기록30864KB / 260ms
최고기록140mss
해결날짜2022/01/04

풀이

코드

"""Solution code for "BOJ 4256. 트리".

- Problem link: https://www.acmicpc.net/problem/4256
- Solution link: http://www.teferi.net/ps/problems/boj/4256

Tags: [DnC]
"""


def main():
    T = int(input())
    for _ in range(T):
        n = int(input())
        preorder = input().split()
        inorder = input().split()

        preorder_iter = iter(preorder)
        inorder_pos_by_node = {node: pos for pos, node in enumerate(inorder)}
        answer = []
        stack = [(0, n)]
        while stack:
            top = stack.pop()
            if isinstance(top, str):
                answer.append(top)
                continue
            beg, end = top
            root = next(preorder_iter)
            root_pos_in_inorder = inorder_pos_by_node[root]
            stack.append(root)
            if root_pos_in_inorder + 1 < end:
                stack.append((root_pos_in_inorder + 1, end))
            if beg < root_pos_in_inorder:
                stack.append((beg, root_pos_in_inorder))

        print(' '.join(answer))


if __name__ == '__main__':
    main()