Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4438 Accepted Submission(s): 2025
A binary tree is a finite set of vertices that is either empty or consists of a root r and two disjoint binary trees called the left and right subtrees. There are three most important ways in which the vertices of a binary tree can be systematically traversed or ordered. They are preorder, inorder and postorder. Let T be a binary tree with root r and subtrees T1,T2.
In a preorder traversal of the vertices of T, we visit the root r followed by visiting the vertices of T1 in preorder, then the vertices of T2 in preorder.
In an inorder traversal of the vertices of T, we visit the vertices of T1 in inorder, then the root r, followed by the vertices of T2 in inorder.
In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit r.
Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence.
InputThe input contains several test cases. The first line of each test case contains a single integer n (1<=n<=1000), the number of vertices of the binary tree. Followed by two lines, respectively indicating the preorder sequence and inorder sequence. You can assume they are always correspond to a exclusive binary tree.
OutputFor each test case print a single line specifying the corresponding postorder sequence.
Sample Input9
1 2 4 7 3 5 8 9 6
4 7 2 1 8 5 9 3 6
7 4 2 8 9 5 6 3 1
Submit#includeusing namespace std; const int N = 1010; int pre[N], in[N], post[N]; // 先序,中序,后序 int k; struct node { int value; node *l, *r; node(int value = 0, node *l = NULL, node *r = NULL) : value(value), l(l), r(r) {} }; void buildtree(int l, int r, int &t, node *&root) //建树 { int flag = -1; for (int i = l; i <= r; i++) //先序的第一个数是根,找到对应的中序位置 { if (in[i] == pre[t]) { flag = i; break; } } if (flag == -1) //结束 return; root = new node(in[flag]); //新建结点 t++; if (flag > l) buildtree(l, flag - 1, t, root->l); if (flag < r) buildtree(flag + 1, r, t, root->r); } void preorder(node *root) { if (root != NULL) { post[k++] = root->value; preorder(root->l); preorder(root->r); } } void inorder(node *root) { if (root != NULL) { inorder(root->l); post[k++] = root->value; inorder(root->r); } } void postorder(node *root) { if (root != NULL) { postorder(root->l); postorder(root->r); post[k++] = root->value; } } void remove_tree(node *root) //释放空间 { if (root == NULL) return; remove_tree(root->l); remove_tree(root->r); delete root; } int main() { int n; while (~scanf("%d", &n)) { for (int i = 1; i <= n; i++) scanf("%d", &pre[i]); for (int i = 1; i <= n; i++) scanf("%d", &in[i]); node *root; int t = 1; buildtree(1, n, t, root); k = 0; // 记录结点个数 postorder(root); for (int i = 0; i < k; i++) printf("%d %c", post[i], i == k - 1 ? 'n' : ' '); remove_tree(root); } return 0; }



