原题链接:oj3344
数据结构实验之二叉树五:层序遍历
Description
已知一个按先序输入的字符序列,如abd,eg,cf,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
Input
输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是一个长度小于50个字符的字符串。
Output
输出二叉树的层次遍历序列。
Sample
Input
2
abd,eg,cf,
xnl,i,u,
Output
abcdefg
xnuli
第一次提交的时候出现了 Compile Error提示(编译错误)
错误原因: 函数名为 struct node *build()
使用时出现了 st->l=build(st);
struct node *build()
{
struct node *st;
if(a[i]==',')
{
i++;
return NULL;
}
else
{
st=(struct node *)malloc(sizeof(struct node));
st->data=a[i++];
st->l=build(st);
st->r=build(st);
}
return st;
}
层次遍历序列:根入队 --> 子树入队 根出队–>子树结点变为根 它的子树入队 它出队 |
---|
A |
正确代码:
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
char a[100];
int i;
struct node
{
int data;
struct node *l,*r;
};
struct node *build() //存
{
struct node *st;
if(a[i]==',')
{
i++;
return NULL;
}
else
{
st=(struct node *)malloc(sizeof(struct node));
st->data=a[i++];
st->l=build();
st->r=build();
}
return st;
}
void pull(struct node *st) //层次
{
struct node *q[100];
int num1=0,num2=0;
q[num1++]=st;
while(num1>num2)
{
if(q[num2]!=NULL)//这里!
{
printf("%c",q[num2]->data);
q[num1++]=q[num2]->l;
q[num1++]=q[num2]->r;
}
num2++;
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
i=0;
struct node *st;
scanf("%s",a);
st=build();
pull(st);
printf("\n");
}
return 0;
}