UVa 122 樹的層次遍歷
阿新 • • 發佈:2017-07-15
push_back oid 按層 roo pri 數組模擬 初始 front 構造
題意:
給定一顆樹, 按層次遍歷輸出。
分析:
用數組模擬二叉樹, bfs即可實現層次遍歷
1 #include <bits/stdc++.h> 2 using namespace std; 3 struct Node{ 4 bool have_value; 5 int v, left, right; 6 void reset(){//用於再次初始化節點 7 init(); 8 } 9 void init(){ 10 have_value = 0; 11 v = left = right = 0; 12 } 13 Node():have_value(false), v(0),left(0), right(0){init();}//構造函數 14 }; 15 const int maxn = 512; 16 Node tree[maxn]; 17 const int root = 1; 18 int cnt, failed; 19 char s[maxn]; 20 void newtree(){ 21 cnt = 1; 22 tree[root].reset(); 23 } 24 void addnode(int v, char* s){ 25 26 intlen = strlen(s) - 1; 27 int u = root; 28 for(int i = 0; i < len; i++){ 29 if(s[i] == ‘L‘){ 30 if(tree[u].left == 0) 31 { 32 tree[u].left = ++cnt; 33 tree[cnt].reset(); 34 u = cnt; 35 } 36 else{ u = tree[u].left;}; 37 } 38 else if(s[i] == ‘R‘){ 39 if(tree[u].right == 0){ 40 tree[u].right = ++cnt; 41 tree[cnt].reset(); 42 u = cnt; 43 } 44 else u = tree[u].right; 45 } 46 } 47 if(tree[u].have_value) failed = true; 48 tree[u].v = v; 49 tree[u].have_value = true; 50 } 51 bool input(){ 52 newtree(); 53 failed = false; 54 for(;;){ 55 if(scanf("%s",s) != 1) return false; 56 if(!strcmp(s,"()")) break; 57 int v; 58 sscanf(&s[1],"%d",&v); 59 addnode(v,strchr(s,‘,‘)+1);//將逗號後的字符串傳遞 60 } 61 return true; 62 } 63 bool bfs(vector<int>& ans){//引用傳遞 64 queue<int> q; 65 q.push(root); 66 while(!q.empty()){ 67 int u = q.front(); 68 q.pop(); 69 if(tree[u].have_value == 0) 70 return false; 71 ans.push_back(tree[u].v); 72 if(tree[u].left != 0){ 73 q.push(tree[u].left); 74 } 75 if(tree[u].right != 0){ 76 q.push(tree[u].right); 77 } 78 } 79 return true; 80 } 81 int main(){ 82 83 while(input()){ 84 vector<int> ans; 85 if(!bfs(ans) || failed) 86 printf("not complete\n"); 87 else { 88 cout <<ans[0]; 89 int alen = ans.size(); 90 for(int i = 1; i < alen; i++){ 91 cout << " " << ans[i]; 92 } 93 puts(""); 94 } 95 } 96 return 0; 97 }
UVa 122 樹的層次遍歷