数据结构实验之二叉树五:层序遍历
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
Hint
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<queue>
using namespace std;
typedef struct node
{
char data;
struct node *l;
struct node *r;
}BTnode,*BT;
char bt[55];
int cnt;
BTnode *Create()
{
BTnode *root;
if(bt[++cnt]==',')
root=NULL;
else
{
root=(BTnode *)malloc(sizeof(BTnode));
root->data=bt[cnt];
root->l=Create();
root->r=Create();
}
return root;
}
void cengci(BTnode *root)
{
queue<BT> q;
BT p;
p=root;
if(p)
q.push(p);
while(!q.empty())
{
p=q.front();
q.pop();
printf("%c",p->data);
if(p->l)
q.push(p->l);
if(p->r)
q.push(p->r);
}
}//用队列依次读取进队父节点和左右孩子节点,然后依次出队列读出
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
cnt=-1;
scanf("%s",bt);
BTnode *root;
root=Create();
cengci(root);
printf("\n");
}
return 0;
}