Tree
InterviewTime limit1sMemory limit192 MB
Given the preorder and inorder traversals of a binary tree, reconstruct the tree and print its postorder traversal.
- Level
Medium4 of 10
- Topics
- Tree, Recursion, Divide and conquer
- Solved
- No attempts yet
Problem
A binary tree is a very important fundamental data structure. Every node of a binary tree has at most two children, and the two children are ordered: the left child comes before the right child. Let be a binary tree with nodes. The nodes of are numbered from to , each with a distinct number. A node that has no children is called a leaf node.
There are three ways to visit every node of a binary tree: preorder, inorder, and postorder traversal. For a node , let denote its left child and its right child; if a child is absent, its value is empty (). The three traversals are defined recursively as follows.
- Preorder: visit the current node first, then traverse the left subtree, then the right subtree.
- Inorder: traverse the left subtree, then visit the current node, then traverse the right subtree.
- Postorder: traverse the left subtree, then the right subtree, and finally visit the current node.
You are given the preorder and inorder traversals of some binary tree . From these two traversals the original binary tree can be reconstructed uniquely. Write a program that outputs the postorder traversal of the same tree.
Input
The first line contains the number of test cases . For each test case, the first line contains the number of nodes (). The nodes of the binary tree are numbered from to , each distinct. The next line contains the preorder traversal, and the line after that contains the inorder traversal, with the numbers separated by spaces. Every input is guaranteed to be a case in which the two traversals determine a unique binary tree.
Output
For each test case, print the postorder traversal of the tree on one line, with the node numbers separated by spaces.