数据结构实验之二叉树五:层序遍历
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
输入
输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是
一个长度小于50个字符的字符串。
输出
输出二叉树的层次遍历序列。
示例输入
2 abd,,eg,,,cf,,, xnl,,i,,u,,
示例输出
abcdefg xnuli
提示
#include <stdio.h>
#include <stdlib.h>#include <string.h>
typedef struct node
{
int num;
struct node *l,*r;
}node,*tree;
char a[100];
int i;
int mount,deepv;
tree creat()
{
tree t;
char ch;
ch=a[i];
i++;
if(ch==',')
{
t=NULL;
}
else
{
t=(tree)malloc(sizeof(node));
t->num=ch;
t->l=creat();
t->r=creat();
}
return t;
}
void show(tree t)
{
int n=0,m=0;
tree p[100];
p[n]=t;
n++;
while(n>m)
{
if(p[m])
{
printf("%c",p[m]->num);
p[n]=p[m]->l;
n++;
p[n]=p[m]->r;
n++;
}
m++;
}
}
void zhong(tree t)
{
if(t!=NULL)
{
zhong(t->l);
printf("%c",t->num);
zhong(t->r);
}
}
void hou(tree t)
{
if(t!=NULL)
{
hou(t->l);
hou(t->r);
printf("%c",t->num);
}
}
void leaf(tree t)
{
if(t!=NULL)
{
if(t->l==NULL&&t->r==NULL)
{
mount++;
}
leaf(t->l);
leaf(t->r);
}
}
int deep(tree t)
{
int deepl,deepr;
if(!t)
{
return 0;
}
else
{
deepl=deep(t->l);
deepr=deep(t->r);
deepv=1+(deepl>deepr?deepl:deepr);
}
return deepv;
}
int main()
{
tree t;
int n,m;
scanf("%d",&m);
while(m)
{
m--;
scanf("%s",a);
i=0;
t=creat();
show(t);
printf("\n");
}
return 0;
}
/*
abd,,e,,cf,,g,,
*/