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;
- }