Tree

Interview

Time limit1sMemory limit192 MB

Summary
Given the preorder and inorder traversals of a binary tree, reconstruct the tree and print its postorder traversal.
Level

Medium4 of 10

Topics
Tree, Recursion, Divide and conquer
Solved
No attempts yet

Problem

A binary tree is a very important fundamental data structure. Every node of a binary tree has at most two children, and the two children are ordered: the left child comes before the right child. Let BTBT be a binary tree with nn nodes. The nodes of BTBT are numbered from 11 to nn, each with a distinct number. A node that has no children is called a leaf node.

There are three ways to visit every node of a binary tree: preorder, inorder, and postorder traversal. For a node vv, let v.leftv.\text{left} denote its left child and v.rightv.\text{right} its right child; if a child is absent, its value is empty (∅\varnothing). The three traversals are defined recursively as follows.

  • Preorder: visit the current node first, then traverse the left subtree, then the right subtree.
  • Inorder: traverse the left subtree, then visit the current node, then traverse the right subtree.
  • Postorder: traverse the left subtree, then the right subtree, and finally visit the current node.

You are given the preorder and inorder traversals of some binary tree BTBT. From these two traversals the original binary tree can be reconstructed uniquely. Write a program that outputs the postorder traversal of the same tree.

Input

The first line contains the number of test cases TT. For each test case, the first line contains the number of nodes nn (1≤n≤1,0001 \le n \le 1{,}000). The nodes of the binary tree are numbered from 11 to nn, each distinct. The next line contains the preorder traversal, and the line after that contains the inorder traversal, with the numbers separated by spaces. Every input is guaranteed to be a case in which the two traversals determine a unique binary tree.

Output

For each test case, print the postorder traversal of the tree on one line, with the node numbers separated by spaces.

Examples2

  1. Example 1

    Input
    2
    4
    3 2 1 4
    2 3 4 1
    8
    3 6 5 4 8 7 1 2
    5 6 8 4 3 1 2 7
    
    Expected output
    2 4 1 3
    5 8 4 6 2 1 7 3
    
  2. Example 2

    Input
    1
    1
    7
    7
    
    Expected output
    7