Sample Output
7 4 2 8 9 5 6 3 1
#include <iostream>
#include"cstdio"
#include"cstring"
#include"cstdlib"
using namespace std;
int pre[1050],ins[1050];
int t;
struct node
{
int data;
node *lch,*rch;
};
node *build(int*pre ,int *ins,int n)
{
if(n<=0) return NULL;
node *p;
p=(node*)malloc(sizeof(node));
p->data=pre[0];
int k;
for(k=0;k<n;k++)
{
if(ins[k]==pre[0])
break;
}
p->lch=build(pre+1,ins,k);
p->rch=build(pre+k+1,ins+k+1,n-k-1);
return p;
}
int num;
void houxu(node *p)
{
if(p!=NULL)
{
houxu(p->lch);
houxu(p->rch);
if(num==0)
{printf("%d",p->data);num++;}
else
printf(" %d",p->data);
}
}
int main()
{
while(~scanf("%d",&t))
{
num=0;
memset(pre,0,sizeof(pre));
memset(ins,0,sizeof(ins));
for(int i=0;i<t;i++)
scanf("%d",&pre[i]);
for(int i=0;i<t;i++)
scanf("%d",&ins[i]);
node *tree;
tree=(node*)malloc(sizeof(node));
tree=build(pre,ins,t);
houxu(tree);
putchar('\n');
}
return 0;
}