#K441. Restore Binary Tree from Traversals
Restore Binary Tree from Traversals
Restore Binary Tree from Traversals
You are given the inorder and preorder traversals of a binary tree with \(N\) nodes. All nodes have unique integer values. Your task is to reconstruct the binary tree and output its postorder traversal.
The inorder traversal visits the left subtree, then the root, then the right subtree, while the preorder traversal visits the root first, then the left subtree, and finally the right subtree.
Formally, given:
- \(N\): the number of nodes in the tree,
- inorder sequence: \(I = [i_1, i_2, \dots, i_N]\),
- preorder sequence: \(P = [p_1, p_2, \dots, p_N]\),
Reconstruct the tree and output its postorder traversal \(O = [o_1, o_2, \dots, o_N]\) where the postorder traversal visits the left subtree, then the right subtree, and finally the root.
Note: The input is read from standard input and the output should be written to standard output.
inputFormat
The first line of input contains an integer \(N\), representing the number of nodes in the binary tree.
The second line contains \(N\) space-separated integers representing the inorder traversal.
The third line contains \(N\) space-separated integers representing the preorder traversal.
outputFormat
Output a single line containing \(N\) space-separated integers representing the postorder traversal of the reconstructed binary tree.
## sample1
1
1
1
</p>