#include <stdio.h>
#include <malloc.h>
typedef struct BiTNode
{
struct BiTNode *lchild,*rchild;
int data;
}*BiTree;
#define maxn 100
int n,post[maxn],in[maxn],pre[maxn];
BiTree Create(int postL,int postR,int inL,int inR)//我们是根据后序和中序,来恢复二叉树
{
int numleft=0,k;
BiTree root;
if(postL>postR)
return NULL;
root=(BiTree)malloc(sizeof(struct BiTNode));
root->data=post[postR];
for(k=inL;k<inR;k++)
if(in[k]==post[postR])
break;//我们记录在中序中找到根节点的位置
numleft=k-inL;//左子树的个数
//左子树在后序区间[postL,post+numleft-1],在中序区间是[inL+1,k-1]
root->lchild=Create(postL,postL+numleft-1,inL,k-1);
//右子树在后序区间是[]
root->rchild=Create(postL+numleft,postR-1,k+1,inR);
return root;
}
void LayerOrder(BiTree root)//层次遍历
{
BiTree queue[maxn],now;
int rear=0,front=0,num=0;
//这里和bfs的套路就一样
queue[rear++]=root;//将根节点入队列
while(rear!=front)
{
now=queue[front++];
//pre[n++]=top->data;
printf("%d",now->data);
num++;
if(num<n)
printf(" ");
if(now->lchild)
queue[rear++]=now->lchild;
if(now->rchild)
queue[rear++]=now->rchild;
}
}
int main()
{
int i;
BiTree root;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&post[i]);
for(i=0;i<n;i++)
scanf("%d",&in[i]);
root=Create(0,n-1,0,n-1);
LayerOrder(root);
}
#include <malloc.h>
typedef struct BiTNode
{
struct BiTNode *lchild,*rchild;
int data;
}*BiTree;
#define maxn 100
int n,post[maxn],in[maxn],pre[maxn];
BiTree Create(int postL,int postR,int inL,int inR)//我们是根据后序和中序,来恢复二叉树
{
int numleft=0,k;
BiTree root;
if(postL>postR)
return NULL;
root=(BiTree)malloc(sizeof(struct BiTNode));
root->data=post[postR];
for(k=inL;k<inR;k++)
if(in[k]==post[postR])
break;//我们记录在中序中找到根节点的位置
numleft=k-inL;//左子树的个数
//左子树在后序区间[postL,post+numleft-1],在中序区间是[inL+1,k-1]
root->lchild=Create(postL,postL+numleft-1,inL,k-1);
//右子树在后序区间是[]
root->rchild=Create(postL+numleft,postR-1,k+1,inR);
return root;
}
void LayerOrder(BiTree root)//层次遍历
{
BiTree queue[maxn],now;
int rear=0,front=0,num=0;
//这里和bfs的套路就一样
queue[rear++]=root;//将根节点入队列
while(rear!=front)
{
now=queue[front++];
//pre[n++]=top->data;
printf("%d",now->data);
num++;
if(num<n)
printf(" ");
if(now->lchild)
queue[rear++]=now->lchild;
if(now->rchild)
queue[rear++]=now->rchild;
}
}
int main()
{
int i;
BiTree root;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&post[i]);
for(i=0;i<n;i++)
scanf("%d",&in[i]);
root=Create(0,n-1,0,n-1);
LayerOrder(root);
}