#include <iostream>
#include <algorithm>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stack>
using namespace std;
#define md 1000000007;
struct tree
{
tree * lson;
tree * rson;
char c;
}mytr;
string p,m,a;
int len;
tree * head;
int prepos=0,aftpos;
void fun_pre_mid(int left,int right,tree * father){
char ch;int midpos;
if(prepos<=len-1){
ch=p[prepos++];
father->c=ch;
for(int i=left;i<=right;i++)
if(m[i]==ch){midpos=i;break;}
tree * tmp=NULL;
tmp=(tree *)malloc(sizeof(tree));
tmp->lson=NULL;tmp->rson=NULL;tmp->c='#';
if(midpos==right&&left<right){
father->rson=NULL;
father->lson=tmp;
fun_pre_mid(left,right-1,tmp);
}
else if(midpos==left&&left<right){
father->lson=NULL;
father->rson=tmp;
fun_pre_mid(left+1,right,tmp);
}
else if(midpos<right&&midpos>left){
tree * tmp1=NULL;
tmp1=(tree *)malloc(sizeof(tree));
tmp1->lson=NULL;tmp1->rson=NULL;tmp1->c='#';
father->lson=tmp;
fun_pre_mid(left,midpos-1,tmp);
father->rson=tmp1;
fun_pre_mid(midpos+1,right,tmp1);
}
}
}
void fun_aft_mid(int left,int right,tree * father){
char ch;int midpos;
if(aftpos>=0){
ch=a[aftpos--];
father->c=ch;
for(int i=left;i<=right;i++)
if(m[i]==ch){midpos=i;break;}
tree * tmp=NULL;
tmp=(tree *)malloc(sizeof(tree));
tmp->lson=NULL;tmp->rson=NULL;tmp->c='#';
if(midpos==right&&left<right){
father->rson=NULL;
father->lson=tmp;
fun_aft_mid(left,right-1,tmp);
}
else if(midpos==left&&left<right){
father->lson=NULL;
father->rson=tmp;
fun_aft_mid(left+1,right,tmp);
}
else if(midpos<right&&midpos>left){
tree * tmp1=NULL;
tmp1=(tree *)malloc(sizeof(tree));
tmp1->lson=NULL;tmp1->rson=NULL;tmp1->c='#';
father->rson=tmp1;
fun_aft_mid(midpos+1,right,tmp1);
father->lson=tmp;
fun_aft_mid(left,midpos-1,tmp);
}
}
}
void preorder(tree * tt){
cout<<tt->c<<" ";
if(tt->lson!=NULL)preorder(tt->lson);
if(tt->rson!=NULL)preorder(tt->rson);
}
void midorder(tree * tt){
if(tt->lson!=NULL)midorder(tt->lson);
cout<<tt->c<<" ";
if(tt->rson!=NULL)midorder(tt->rson);
}
void aftorder(tree * tt){
if(tt->lson!=NULL)aftorder(tt->lson);
if(tt->rson!=NULL)aftorder(tt->rson);
cout<<tt->c<<" ";
}
int main()
{
cout<<"pre order"<<endl;
cin>>p;len=p.length();
cout<<"mid order"<<endl;
cin>>m;
head = new tree;
fun_pre_mid(0,len-1, head);
cout<<"pre:"<<endl;
preorder( head);puts("");
cout<<"mid:"<<endl;
midorder( head);puts("");
cout<<"aft:"<<endl;
aftorder( head);puts("");
puts("------------------------------");
cout<<"mid order"<<endl;
cin>>m;
cout<<"aft order"<<endl;
cin>>a;len=a.length();aftpos=len-1;
head = new tree;
fun_aft_mid(0,len-1, head);
cout<<"pre:"<<endl;
preorder( head);puts("");
cout<<"mid:"<<endl;
midorder( head);puts("");
cout<<"aft:"<<endl;
aftorder( head);
return 0;
}