#K94007. Construct Binary Tree and Obtain Postorder Traversal
Construct Binary Tree and Obtain Postorder Traversal
Construct Binary Tree and Obtain Postorder Traversal
You are given two traversal sequences of a binary tree: the preorder sequence and the inorder sequence. All elements in the tree are distinct, which guarantees that the binary tree can be uniquely reconstructed.
Your task is to reconstruct the binary tree using the given sequences and then compute its postorder traversal. In postorder traversal, you visit the left subtree, then the right subtree, and finally the root node.
Recall the classic tree reconstruction formulas: if \( pre = [root, \ldots] \) and \( in = [\ldots, root, \ldots] \), then the left subtree corresponds to the portion in inorder before the root, and the right subtree corresponds to the portion after the root.
inputFormat
The input is read from standard input (stdin) and consists of three lines:
- An integer
n
representing the number of nodes in the tree. n
space-separated integers representing the preorder traversal of the tree.n
space-separated integers representing the inorder traversal of the tree.
outputFormat
Output the postorder traversal of the binary tree in a single line. The node values should be space-separated, and the output should be written to standard output (stdout).
## sample7
1 2 4 5 3 6 7
4 2 5 1 6 3 7
4 5 2 6 7 3 1