Description
已知一个按先序输入的字符序列,如abd,eg,cf,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
Input
输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是一个长度小于50个字符的字符串。
Output
输出二叉树的层次遍历序列。
Sample
Input
2
abd,eg,cf,
xnl,i,u,
Output
abcdefg
xnuli
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<malloc.h>
typedef struct node
{
struct node *l,*r;
char data;
} node,*Tree;
char s[1100],ch;
int k;
void Creat(Tree&T)
{
ch = s[k++];
if(ch == ',')
T = NULL;
else
{
T = (struct node*)malloc(sizeof(node));
T -> data = ch;
Creat(T->l);
Creat(T->r);
}
}
void ceng(Tree&T)
{
if(T==NULL)//这里注意一定要加上,否则会RTE
return ;
Tree a[1100];
int i=0,n=0;
a[n++] = T;
while(i<n)
{
if(a[i])
{
if(a[i]->l!=NULL)
a[n++] = a[i]->l;
if(a[i]->r!=NULL)
a[n++] = a[i]->r;
}
i++;
}
for(int j=0;j<n;j++)
printf("%c",a[j]->data);
//printf("\n");
}
int main()
{
Tree T;
int t;
scanf("%d",&t);
getchar();
while(t--)
{
k = 0;
//T = NULL;
//gets(s);
scanf("%s",s);
Creat(T);
ceng(T);
printf("\n");
}
return 0;
}