题目要求是:给出一棵二叉树的后序遍历序列和中序遍历序列,求这棵二叉树的层序遍历序列。
#include <cstdio>
#include <queue>
using namespace std;
const int maxn = 35;
int post[maxn] = {0};
int in[maxn] = {0};
int traversal[maxn] = {0};
int N;
struct node{
int data;
node *lchild;
node *rchild;
};
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(k = inL; k <= inR; k++){
if(in[k] == post[postR])
break;
}
int numLeft = k - inL;
root->lchild = create(postL, postL+numLeft-1, inL, k-1);
root->rchild = create(postL+numLeft, postR-1, k+1, inR);
return root;
}
void bfs(node *root)
{
queue<node *> q;
q.push(root);
int k = 1;
while(!q.empty()){
node *top = q.front();
q.pop();
traversal[k++] = top->data;
if(top->lchild != NULL)
q.push(top->lchild);
if(top->rchild != NULL)
q.push(top->rchild);
}
}
int main()
{
scanf("%d", &N);
for(int i = 1; i <= N; i++)
scanf("%d", &post[i]);
for(int i = 1; i <= N; i++)
scanf("%d", &in[i]);
node *root = create(1, N, 1, N);
bfs(root);
for(int i = 1; i <= N; i++){
if(i != N)
printf("%d ", traversal[i]);
else
printf("%d\n", traversal[i]);
}
return 0;
}