数据结构实验之二叉树五:层序遍历
Time Limit: 1000ms Memory limit: 65536K
题目描述
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
输入
输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是
一个长度小于50个字符的字符串。
输出
输出二叉树的层次遍历序列。
示例输入
2 abd,,eg,,,cf,,, xnl,,i,,u,,
示例输出
abcdefg xnuli
提示
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
char st[50];
int i;
struct Tnode
{
char d;
Tnode *l,*r;
};
Tnode *CreatTree()
{
Tnode *p;
if(st[i++]==',')
p= NULL;
else
{
p=new Tnode;
p->d=st[i-1];
p->l=CreatTree();
p->r=CreatTree();
}
return p;
}
void level_order(Tnode *p)
{
queue<Tnode *>q;
if(p)
q.push(p);
while(!q.empty())
{
Tnode *k=q.front();
cout<<k->d;
if(k->l)
q.push(k->l);
if(k->r)
q.push(k->r);
q.pop();
}
}
int main()
{
int t;
while(cin>>t)
{
while(t--)
{
i=0;
cin>>st;
Tnode *root=CreatTree();
level_order(root);
cout<<endl;
}
}
return 0;
}