Description
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历和层序遍历。
Input
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
Output
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列。
Sample
Input
2
abdegcf
dbgeafc
xnliu
lnixu
Output
dgebfca
abcdefg
linux
xnuli
#include <bits/stdc++.h>
using namespace std;
const int maxx=1e5+100;
struct node
{
char data;
node*l,*r;
} *q[55];
node* creat(char pre[],char mid[],int len)
{
if(len<=0)
return NULL;
node *root=new node();
root->data=pre[0];
int i=0;
for(i; i<len; i++)
{
if(mid[i]==pre[0])
break;
}
root->l=creat(pre+1,mid,i);
root->r=creat(pre+i+1,mid+i+1,len-i-1);
return root;
}
void level(node*root)
{
if(root==NULL)
return ;
int head=1,tail=1;
q[tail++]=root;
while(head<tail)
{
cout<<q[head]->data;
if(q[head]->l)
q[tail++]=q[head]->l;
if(q[head]->r)
q[tail++]=q[head]->r;
head++;
}
}
void finall(node*root)
{
if(root)
{
finall(root->l);
finall(root->r);
cout<<root->data;
}
}
int main()
{
int t;
while(cin>>t)
{
while(t--)
{
node *root=new node();
char s1[maxx],s2[maxx];
cin>>s1>>s2;
root=creat(s1,s2,strlen(s1));
finall(root);
cout<<endl;
level(root);
cout<<endl;
}
}
return 0;
}