Problem 416
Construct Tree from Inorder and Postorder
Medium · 20 pts · Tree, Divide and Conquer, Hash Table
Problem
A binary tree with distinct values is described by its inorder traversal (left subtree, node, right subtree) and its postorder traversal (left subtree, right subtree, node). Rebuild the tree and print its preorder traversal (node, left subtree, right subtree). The last element of the postorder is always the root; its position in the inorder splits the remaining values into the left and right subtrees.
Input
First line: N. Second line: the inorder traversal. Third line: the postorder traversal.
Output
Print the preorder traversal, separated by spaces.
Constraints
1 <= N <= 3000; -3000 <= value <= 3000; values are distinct
Example input
5 9 3 15 20 7 9 15 7 20 3
Example output
3 9 20 15 7
Explanation
The postorder 9 15 7 20 3 ends with 3, so 3 is the root. In the inorder 9 3 15 20 7, 9 is left of 3 and 15 20 7 is right of it. Rebuilding gives the preorder 3 9 20 15 7.