PAT A1020

#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);
 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值