层次遍历的时候要考虑root是否一开始就为NULL;
如果不考虑,会出现runtime error;
数据结构实验之二叉树五:层序遍历
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
Input
输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是
一个长度小于50个字符的字符串。
Output
输出二叉树的层次遍历序列。
Example Input
2 abd,,eg,,,cf,,, xnl,,i,,u,,
Example Output
abcdefg xnuli
#include <stdio.h>
#include <stdlib.h>
int k;
char a[100];
struct bittree
{
char data;
struct bittree * ltree,* rtree;
};
void cengci(struct bittree * root)
{
if(root==NULL)
{
return ;
}
int f,r;
f=1;r=1;
struct bittree * s[100],*p;
s[1]=root;
while(f<=r)
{
p=s[f++];
printf("%c",p->data);
if(p->ltree!=NULL)
{
s[++r]=p->ltree;
}
if(p->rtree!=NULL)
{
s[++r]=p->rtree;
}
}
}
struct bittree * create(struct bittree * root)
{
root=(struct bittree *)malloc(sizeof(struct bittree));
if(a[k]==',')
{
root=NULL;
k++;
}
else
{
root->data=a[k++];
root->ltree=create(root->ltree);
root->rtree=create(root->rtree);
}
return root;
}
int main()
{
int t;
struct bittree * root;
scanf("%d",&t);
getchar();
while(t--)
{
k=0;
gets(a);
root=create(root);
cengci(root);
printf("\n");
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int k;
char a[100];
struct bittree
{
char data;
struct bittree * ltree,* rtree;
};
void cengci(struct bittree * root)
{
if(root==NULL)
{
return ;
}
int f,r;
f=1;r=1;
struct bittree * s[100],*p;
s[1]=root;
while(f<=r)
{
p=s[f++];
printf("%c",p->data);
if(p->ltree!=NULL)
{
s[++r]=p->ltree;
}
if(p->rtree!=NULL)
{
s[++r]=p->rtree;
}
}
}
struct bittree * create(struct bittree * root)
{
root=(struct bittree *)malloc(sizeof(struct bittree));
if(a[k]==',')
{
root=NULL;
k++;
}
else
{
root->data=a[k++];
root->ltree=create(root->ltree);
root->rtree=create(root->rtree);
}
return root;
}
int main()
{
int t;
struct bittree * root;
scanf("%d",&t);
getchar();
while(t--)
{
k=0;
gets(a);
root=create(root);
cengci(root);
printf("\n");
}
return 0;
}