#K40137. Reconstruct a BST from Inorder and Level-Order Traversals
Reconstruct a BST from Inorder and Level-Order Traversals
Reconstruct a BST from Inorder and Level-Order Traversals
You are given two sequences representing the inorder and level-order traversals of a binary search tree (BST). Your task is to reconstruct the original BST and output its level-order traversal.
The inorder traversal of a BST gives the nodes in sorted order. The level-order traversal visits nodes level by level from top to bottom.
Recall that for any node in a BST, its left subtree contains nodes strictly less than the node's value and its right subtree contains nodes strictly greater than the node's value. In mathematical terms, if r is a root, then for any node v in the left subtree,
$$v < r$$
and for any node w in the right subtree,
$$w > r.$$
You need to use these properties and the given traversals to rebuild the tree. Then, output the level-order traversal of the constructed tree.
inputFormat
The input is taken from standard input and has the following format:
- The first line contains an integer N, the number of nodes in the BST.
- The second line contains N space-separated integers representing the inorder traversal.
- The third line contains N space-separated integers representing the level-order traversal.
Note: If N is 0, the subsequent lines will be empty.
outputFormat
Output a single line to standard output containing the level-order traversal of the reconstructed BST. The node values should be separated by a single space.
## sample7
4 8 10 12 14 20 22
20 8 22 4 12 10 14
20 8 22 4 12 10 14