SDUT 3344 數據結構實驗之二叉樹五:層序遍歷

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

示例程序

 
按照先序建立二叉樹然後再進行層次遍歷,代碼如下

  1. #include <cstdio>  
  2. #include <cstring>  
  3. #include <algorithm>  
  4. using namespace std;  
  5. char s[50+5];  
  6. int ans;  
  7. struct tree  
  8. {  
  9.     char data;  
  10.     tree *l, *r;  
  11. }*q[50+5];  
  12. tree *build()  //遞歸先序建立二叉樹
  13. {  
  14.     char c=s[ans++];  
  15.     tree *root;  
  16.     if(c==',')  
  17.         root=NULL;  
  18.     else  
  19.     {  
  20.         root=new tree;  
  21.         root->data=c;  
  22.         root->l=build();  
  23.         root->r=build();  
  24.     }  
  25.     return root;  
  26. }  
  27. void level(tree *root)  //基於隊列的層次遍歷
  28. {  
  29.     if(!root) return ;  
  30.     int head=1, tail=1;  
  31.     q[tail++]=root;  
  32.     while(head<tail)  
  33.     {  
  34.         printf("%c", q[head]->data);  
  35.         if(q[head]->l)  
  36.         {  
  37.             q[tail++]=q[head]->l;  
  38.         }  
  39.         if(q[head]->r)  
  40.         {  
  41.             q[tail++]=q[head]->r;  
  42.         }  
  43.         head++;  
  44.     }  
  45. }  
  46. int main()  
  47. {  
  48.     int t;  
  49.     while(~scanf("%d", &t))  
  50.     {  
  51.         while(t--)  
  52.         {  
  53.             ans=0;  
  54.             scanf("%s", s);  
  55.             tree *root=build();  
  56.             level(root);  
  57.             printf("\n");  
  58.         }  
  59.     }  
  60.     return 0;  
  61. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章