1. 程式人生 > >UVa 122 Trees on the level(鏈式二叉樹的建立和層次遍歷)

UVa 122 Trees on the level(鏈式二叉樹的建立和層次遍歷)

構建 void target .net color 鏈接 struct failed div

題目鏈接:

https://cn.vjudge.net/problem/UVA-122

  1 /*
  2 問題
  3 給出每個節點的權值和路線,輸出該二叉樹的層次遍歷序列。
  4 
  5 解題思路
  6 根據輸入構建鏈式二叉樹,再用廣度優先遍歷保存權值最後輸出。 
  7 */ 
  8 #include<cstdio>
  9 #include<cstring>
 10 #include<vector>
 11 #include<queue>
 12 using namespace std;
 13 const int maxn=110;
 14
bool failed; 15 16 struct NODE{ 17 bool have_value; 18 int v; 19 NODE *left,*right; 20 NODE() : have_value(false),left(NULL),right(NULL){}; 21 }; 22 NODE* newnode(){ 23 return new NODE(); 24 } 25 NODE* root; 26 27 bool read_input(); 28 void addnode(int v,char *s);
29 bool bfs(vector<int> &ans); 30 void remove_tree(NODE* u){ 31 if(u == NULL) return; 32 remove_tree(u->left); 33 remove_tree(u->right); 34 delete u; 35 } 36 37 int main() 38 { 39 //freopen("E:\\testin.txt","r",stdin); 40 vector<int> ans; 41 while
(read_input()){ 42 if(failed || !bfs(ans)) 43 printf("not complete\n"); 44 else{ 45 int i; 46 for(i=0;i<ans.size()-1;i++) 47 printf("%d ",ans[i]); 48 printf("%d\n",ans[i]); 49 } 50 } 51 return 0; 52 } 53 54 bool bfs(vector<int> &ans){ 55 queue<NODE*> q; 56 ans.clear(); 57 q.push(root); 58 59 while(!q.empty()){ 60 NODE* u =q.front(); q.pop(); 61 if(!u->have_value) return false; 62 ans.push_back(u->v); 63 64 if(u->left != NULL) q.push(u->left); 65 if(u->right != NULL) q.push(u->right); 66 } 67 return true; 68 } 69 void addnode(int v,char *s){ 70 int len=strlen(s); 71 72 NODE* u= root; 73 for(int i=0;i<len;i++){ 74 if(s[i] == L){ 75 if(u->left == NULL) 76 u->left= newnode(); 77 u=u->left; 78 }else if(s[i] == R){ 79 if(u->right == NULL) 80 u->right= newnode(); 81 u=u->right; 82 } 83 } 84 85 if(u->have_value) failed=true; 86 u->v= v; 87 u->have_value=true; 88 } 89 bool read_input(){ 90 char s[maxn]; 91 failed=false; 92 remove_tree(root); 93 root=newnode(); 94 for(;;){ 95 if(scanf("%s",s) != 1) return false; 96 if(!strcmp(s,"()")) break; 97 int v; 98 sscanf(s+1,"%d",&v); 99 addnode(v,strchr(s,,)+1); 100 } 101 return true; 102 }

UVa 122 Trees on the level(鏈式二叉樹的建立和層次遍歷)