#include<iostream>
#include<malloc.h>
#include<queue>
#define maxn 35
using namespace std;
int in[maxn],post[maxn];
struct stu
{
int num;
stu *l,*r;
};
int n;
void build(stu *&s,int a,int b,int aa,int bb)
{
s=(stu*)malloc(sizeof(stu));
s->num=post[bb];
s->l=s->r=NULL;
int x=a;
while(in[x]!=post[bb]) x++;
if(a<=x-1) build(s->l,a,x-1,aa,aa+x-1-a);
if(x+1<=b) build(s->r,x+1,b,bb-b+x,bb-1);
}
void pi(stu *s)
{
queue<stu*>q;
cout<<s->num;
if(s->l) q.push(s->l);
if(s->r) q.push(s->r);
while(q.size())
{
stu* w=q.front();
q.pop();
cout<<" "<<w->num;
if(w->l) q.push(w->l);
if(w->r) q.push(w->r);
}
}
int main()
{
while(cin>>n)
{
for(int i=1;i<=n;i++) cin>>post[i];
for(int i=1;i<=n;i++) cin>>in[i];
stu *p;
build(p,1,n,1,n);
//cout<<p->num<<endl;
pi(p);
cout<<endl;
}
return 0;
}
模板-根据中序,后序建树层次遍历输出
最新推荐文章于 2021-04-25 14:49:57 发布