Construct Binary Tree from Preorder and Inorder Traversal

MediumTrees
Next
TreeDivide and ConquerHash Map

You are given the preorder and inorder traversals of a binary tree with distinct values. Rebuild the tree and print its postorder traversal (left subtree, right subtree, node).

Input

Line 1: n, the number of nodes. Line 2: the preorder traversal. Line 3: the inorder traversal.

Output

Print the postorder traversal on one line.

Constraints

1 <= n <= 1000 All values are distinct.

Example 1
Input
5
3 9 20 15 7
9 3 15 20 7
Output
9 15 7 20 3

The rebuilt tree has 3 as root with 9 on the left and 20 (children 15, 7) on the right.

Hints

Construct Binary Tree from Preorder and Inorder Traversal - Medium Trees Problem | Skill Shiksha