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