数据结构实验之二叉树五:层序遍历
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<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
struct node
{
char data;//注意数据类型
struct node *l,*r;
};
int count;
char a[1010];
struct node *creat()//按照先序序列建树
{
struct node *root;
root=(struct node *)malloc(sizeof(struct node ));
if(a[count++]==',')
root=NULL;
else
{
root->data=a[count-1];
root->l=creat();
root->r=creat();
}
return root;
};
void leveltraverse(struct node *root)//层序遍历
{
int in=0;
int out=0;
struct node *q[1010];
q[in++]=root;//根结点入队列
while(in>out)//队列不为空
{
if(q[out])
{
cout<<q[out]->data;
q[in++]=q[out]->l;
q[in++]=q[out]->r;
}
out++;
}
}
int main()
{
int i,n;
struct node *root;
while(~scanf("%d",&n))
{
for(i=0;i<n;i++)
{
scanf("%s",a);
count=0;
root=creat();
leveltraverse(root);
cout<<endl;
}
}
return 0;
}