Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
#include <iostream>
#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std;
int n;
int in[31], post[31], level[31];
typedef struct node
{
int data;
node *l_child;
node *r_child;
}node;
void input()
{
//
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> post[i];
}
for(int i = 0; i < n; i++)
cin >> in[i];
}
node *create(int postL, int postR, int inL, int inR)
{
if(postL > postR)
{
return NULL;
}
node *root = new node;
root->data = post[postR];
int k;
for(int i = inL; i <= inR; i++)
{
if(in[i] == root->data)
{
k = i;
break;
}
}
int left_num = k - inL;
root->l_child = create(postL, postL+left_num-1, inL, k-1);
root->r_child = create(postL+left_num, postR-1, k+1, inR);
return root;
}
void level_order(node *root)
{
queue<node*> que;
que.push(root);
int len = 0;
while(!que.empty())
{
node *father = que.front();
que.pop();
level[len++] = father->data;
if(father->l_child != NULL)
{
que.push(father->l_child);
}
if(father->r_child != NULL)
{
que.push(father->r_child);
}
}
}
int main()
{
/*1020 Tree Traversals (25 分)*/
#ifndef ONLINE_JUDGE
freopen("test.txt", "r", stdin);
#endif // ONLINE_JUDGE
input();
node *root = create(0, n-1, 0, n-1);
level_order(root);
cout << level[0];
for(int i = 1; i < n; i++)
cout <<" " << level[i];
return 0;
}