Returns the central and forward traversal of a binary tree, and outputs its post-order traversal.
Input
There are multiple groups of data in this question, and the input is processed until the end of the file.
The first row of each data group contains an integer n, indicating that this binary tree has a total of n nodes.
Each row in the next row contains n integers, indicating the ordinal traversal of the tree.
Each row in the next row contains n integers, indicating the forward traversal of the tree.
3 <= n <= 100
Output
Each group of outputs contains a row, indicating the post-order traversal of the tree.
Sample Input
7
4 2 5 1 6 3 7
1 2 4 5 3 6 7
Sample Output
4 5 2 6 7 3 1
The Code is as follows:
#include
#include
#include
#include
#define MAXN 10005#define RST(N)memset(N, 0, sizeof(N))using namespace std;int inorder_table[MAXN];int preorder_table[MAXN];int position[MAXN], n;void work( int in_l, int in_r, int pre_l, int pre_r){int pos;if(in_l == in_r) {cout << inorder_table[in_l] << ' ';return;}pos = position[preorder_table[pre_l]];if(in_l <= ( pos - 1)) work(in_l, pos-1, pre_l+1, pos-in_l+pre_l);if((pos + 1) <= in_r) work(pos+1, in_r, pre_r-in_r+pos+1, pre_r);cout << inorder_table[pos] << ' ';}int main(){while(cin >> n) { RST(inorder_table), RST(preorder_table), RST(position);for(int i=1; i<=n; i++) {cin >> inorder_table[i];position[inorder_table[i]] = i;}for(int i=1; i<=n; i++) cin >> preorder_table[i];work(1, n, 1, n);cout << endl;}return 0;}