#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std;
int post[100];
int in[100];
typedef struct Node{
char data;
Node *lchild, *rchild;
}Node, *BiTree;
void create(BiTree &T, int postL, int postR, int inL, int inR){
if(postL > postR) return;
T = (BiTree)malloc(sizeof(BiTree));
T->data = post[postR];
T->lchild = NULL;
T->rchild = NULL;
int k;
for(k=inL; k<=inR; k++){
if(in[k] == post[postR]) break;
}
int numleft = k - inL;
create(T->lchild, postL, postL+numleft-1, inL, k-1);
create(T->rchild, postL+numleft, postR-1, k+1, inR);
}
void layerorder(BiTree T){
queue<BiTree> q;
q.push(T);
while(!q.empty()){
BiTree temp = q.front();
q.pop();
printf("%d", temp->data);
if(temp->lchild != NULL) q.push(temp->lchild);
if(temp->rchild != NULL) q.push(temp->rchild);
if(!q.empty()) printf(" ");
}
}
int main(){
BiTree T;
int n;
scanf("%d", &n);
for(int i=0; i<n; i++){
scanf("%d", &post[i]);
}
for(int i=0; i<n; i++){
scanf("%d", &in[i]);
}
create(T, 0, n-1, 0, n-1);
layerorder(T);
return 0;
}
通过二叉树的前序和中序推出二叉树,然后进行层序遍历