http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=3344
数据结构实验之二叉树五:层序遍历
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
输入
输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是
一个长度小于50个字符的字符串。
输出
输出二叉树的层次遍历序列。
示例输入
2 abd,,eg,,,cf,,, xnl,,i,,u,,
示例输出
abcdefg xnuli
提示
来源
xam
示例程序
- #include <cstdio>
- #include <cstring>
- #include <algorithm>
- using namespace std;
- char s[50+5];
- int ans;
- struct tree
- {
- char data;
- tree *l, *r;
- }*q[50+5];
- tree *build() //递归先序建立二叉树
- {
- char c=s[ans++];
- tree *root;
- if(c==',')
- root=NULL;
- else
- {
- root=new tree;
- root->data=c;
- root->l=build();
- root->r=build();
- }
- return root;
- }
- void level(tree *root) //基于队列的层次遍历
- {
- if(!root) return ;
- int head=1, tail=1;
- q[tail++]=root;
- while(head<tail)
- {
- printf("%c", q[head]->data);
- if(q[head]->l)
- {
- q[tail++]=q[head]->l;
- }
- if(q[head]->r)
- {
- q[tail++]=q[head]->r;
- }
- head++;
- }
- }
- int main()
- {
- int t;
- while(~scanf("%d", &t))
- {
- while(t--)
- {
- ans=0;
- scanf("%s", s);
- tree *root=build();
- level(root);
- printf("\n");
- }
- }
- return 0;
- }