Problem 160
Construct Tree from Preorder and Inorder
Medium · 20 pts · Tree, Divide and Conquer, Hash Table
Problem
You are given the preorder and inorder traversals of a binary tree with distinct values. Rebuild the tree and print its postorder traversal. The first value in preorder is the root. Find it in the inorder sequence: everything to its left belongs to the left subtree and everything to its right to the right subtree. The sizes of these parts tell you how to split the rest of the preorder sequence, and you can rebuild both subtrees recursively. A hash map from value to inorder position makes each lookup O(1).
Input
First line: integer N. Second line: the preorder traversal. Third line: the inorder traversal.
Output
Print the postorder traversal, space-separated.
Constraints
1 <= N <= 3000; -3000 <= value <= 3000; values are distinct
Example input
5 3 9 20 15 7 9 3 15 20 7
Example output
9 15 7 20 3
Explanation
Preorder starts with 3, so 3 is the root. In inorder 9 3 15 20 7, the left subtree is 9 and the right subtree holds 15 20 7. In preorder the right part is 20 15 7, so 20 is its root, with 15 on the left and 7 on the right. Postorder is 9 15 7 20 3.