数据结构实验之二叉树五:层序遍历
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
输入
输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是
一个长度小于50个字符的字符串。
输出
输出二叉树的层次遍历序列。
示例输入
2 abd,,eg,,,cf,,, xnl,,i,,u,,
示例输出
abcdefg xnuli
二叉树的层序遍历,先按先序输入,输出的时候设置一个q【】结构体数组,用来记录,in代表入,out代表出
if(q[out
]) 就可以输出了,试着跟着代码走一遍,你就回很明白
注意!!!!!!
输出完了之后一定要加回车,被这个地方卡了好几次,还傻乎乎的去找代码的bug -_-|| =_=|||||!!!!
#include <bits/stdc++.h>
using namespace std;
char s[10001];
struct node
{
char data;
struct node *lc,*rc;
};
int l;
struct node * creat()
{
char c=s[l++];
struct node *root;
if(c==',')
{
return NULL;
}
else
{
root=new struct node ;
root->data=c;
root->lc=creat();
root->rc=creat();
}
return root;
}
void ceng(struct node *root)
{
int out=0;
int in=0;
struct node *q[10010];
q[in++]=root;
while(out<in)
{
if(q[out])
{
printf("%c",q[out]->data);
q[in++]=q[out]->lc;
q[in++]=q[out]->rc;
}
out++;
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
l=0;
scanf("%s",s);
struct node *root;
root=creat();
ceng(root);
cout<<endl;//注意!!!!!
}
return 0;
}