#include<stdio.h>
#include<stdlib.h>
#include<cstdio>
#include<iostream>
#include<stack>
#include<queue>
#include<string.h>
using namespace std;
#define N 100
int Pre[N],In[N];
int n,Pi,flag=0;
typedef struct BiTNode
{
int TreeName;
struct BiTNode *Lchild,*Rchild;
}BiTNode,*BiTree;
int Input()
{
stack<int> qs;
int a,n,i=1,j=1;
char s[N];
scanf("%d",&n);
for(int k=1;k<=2*n;k++)
{
scanf("%s",s);
if(strcmp(s,"Push")==0)
{
scanf("%d",&a);
Pre[i++]=a;
qs.push(a);
}
else if(strcmp(s,"Pop")==0)
{
In[j++]=qs.top();
qs.pop();
}
}
return n;
}
void CreateBitree(BiTree &A,int Ini,int Inj)
{
int name;
int Ii=Ini,Ij=Inj,p;
name=Pre[Pi++];
for(int i=Ini;i<=Inj;i++)
{
if(In[i]==name)
{
p=i;
break;
}
}
A = new BiTNode;
A -> TreeName = name;
if(p==Ini)
A->Lchild=NULL;
else
CreateBitree(A->Lchild,Ii,p-1);
if(p==Inj)
A->Rchild=NULL;
else
CreateBitree(A->Rchild,p+1,Ij);
}
void PostOrder(BiTree bt)
{
if(bt!=NULL)
{
PostOrder(bt->Lchild);
PostOrder(bt->Rchild);
if(flag==0)
{
printf("%d",bt->TreeName);
flag++;
}
else
printf(" %d",bt->TreeName);
}
}
int main()
{
BiTree A;
n=Input();
Pi=1;
CreateBitree(A,1,n);
PostOrder(A);
return 0;
}
03-树3 Tree Traversals Again
最新推荐文章于 2022-07-26 19:12:27 发布