标签:bre scan 传递 input using c++ clu images log
给定一颗树, 按层次遍历输出。
用数组模拟二叉树, 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 int len = 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 }
标签:bre scan 传递 input using c++ clu images log
原文地址:http://www.cnblogs.com/Jadon97/p/7181796.html