PAT A1086

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define maxn 1010
typedef struct BST
{
struct BST *lchild, *rchild;
int data;
}*Bst;
int n,pre[maxn],in[maxn],post[maxn];
Bst create(int preL,int preR,int inL,int inR)//已知前序,中序 求后序
{
Bst root;
int k,numleft;
root=(Bst)malloc(sizeof(struct BST));
root->data=pre[preL];//根节点的值
if(preL>preR)
return NULL;
for(k=inL;k<inR;k++)
if(in[k]==pre[preL])
break;
numleft=k-inL;//左子树的个数;
root->lchild=create(preL+1,preL+numleft,inL,k-1);
root->rchild=create(preL+numleft+1,preR,k+1,inR);
return root;
}
int num=0;
void postOrder(Bst root)
{
if(root==NULL)
return ;
postOrder(root->lchild);
postOrder(root->rchild);
printf("%d",root->data);
num++;
if(num<n)
printf(" ");
}
int main()
{
int i,id,d[maxn],top=0,pre_num=0,in_num=0;//这里我们就用的额是一个数组模拟了一个栈,来实现功能
char str[5];
Bst root;
scanf("%d",&n);
for(i=0;i<2*n;i++)
{
scanf("%s",str);
if(strcmp(str,"Push")==0)
{
scanf("%d",&id);
pre[pre_num++]=id;
d[top++]=id;//我们入栈
}
else if(strcmp(str,"Pop")==0)
{
in[in_num++]=d[--top];//
}
//getchar();
}
root=create(0,n-1,0,n-1);
postOrder(root);
return 0;
}

猜你喜欢

转载自blog.csdn.net/ZSS1753936255/article/details/71302580