求二叉树的层次遍历
Time Limit: 1000 ms
Memory Limit: 65536 KiB
Problem Description
已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。
Input
输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。
Output
每组输出这颗二叉树的层次遍历。
Sample Input
2 abc bac abdec dbeac
Sample Output
abc abcde
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char num;
struct node *l,*r;
};
struct node *kk(char i[],int n,char j[])
{
if(n<=0)
return NULL;
struct node *root;
root=(struct node *)malloc(sizeof(struct node));
root->num=i[0];
int v;
for(v=0;v<n;v++)
if(i[0]==j[v])break;
root->l=kk(i+1,v,j);
root->r=kk(i+v+1,n-v-1,j+v+1);
return root;
};
void zz(struct node *t)
{
if(t==NULL)
return ;
int f=1,i=1;
struct node *s[1000],*q;
s[1]=t;
while(f<=i)
{
q=s[f++];
printf("%c",q->num);
if(q->l!=NULL)
{
s[++i]=q->l;
}
if(q->r!=NULL)
{
s[++i]=q->r;
}
}
}
int main()
{
int a,b;
char i[1000],j[1000];
struct node *root,*t;
scanf("%d",&a);
while(a--)
{
scanf("%s %s",i,j);
b=strlen(i);
root=kk(i,b,j);
t=root;
zz(t);
printf("\n");
}
return 0;
}