uva 122 trees on the level——yhx
题目如下:Given a sequence of binary trees, you are to write a program that prints a level-order traversal of each tree. In this problem each node of a binary tree contains a positive integer and all binary trees have have fewer than 256 nodes.
In a level-order traversal of a tree, the data in all nodes at a given level are printed in left-to-right order and all nodes at level k are printed before all nodes at level k+1.
For example, a level order traversal of the tree
is: 5, 4, 8, 11, 13, 4, 7, 2, 1.
In this problem a binary tree is specified by a sequence of pairs (n,s) where n is the value at the node whose path from the root is given by the string s. A path is given be a sequence of L's and R's where L indicates a left branch and R indicates a right branch. In the tree diagrammed above, the node containing 13 is specified by (13,RL), and the node containing 2 is specified by (2,LLR). The root node is specified by (5,) where the empty string indicates the path from the root to itself. A binary tree is considered to be completely specified if every node on all root-to-node paths in the tree is given a value exactly once.
1 #include<cstdio> 2 #include<cstring> 3 #include<queue> 4 using namespace std; 5 struct node 6 { 7 int lch,rch,val; 8 bool b; 9 }a[260],n1,n2; 10 int n,ans[260]; 11 int rd() 12 { 13 int i,j,k,p,x,y,z,rt; 14 char s[300],c1,c2; 15 memset(a,0,sizeof(a)); 16 n=1; 17 if (scanf("%s",s)==-1) return 0; 18 rt=1; 19 while (1) 20 { 21 if (s[1]==')') break; 22 x=0; 23 for (i=1;s[i]!=',';i++) 24 x=x*10+s[i]-'0'; 25 p=1; 26 for (i=i+1;i<=strlen(s)-2;i++) 27 if (s[i]=='L') 28 { 29 if (!a[p].lch) a[p].lch=++n; 30 p=a[p].lch; 31 } 32 else 33 { 34 if (!a[p].rch) a[p].rch=++n; 35 p=a[p].rch; 36 } 37 if (a[p].b) rt=-1; 38 a[p].val=x; 39 a[p].b=1; 40 scanf("%s",s); 41 } 42 return rt; 43 } 44 queue<int> q; 45 int main() 46 { 47 int i,j,k,l,m,p,x,y,z; 48 bool b; 49 while (1) 50 { 51 x=rd(); 52 if (!x) break; 53 if (x==-1) 54 { 55 printf("not complete\n"); 56 continue; 57 } 58 while (!q.empty()) q.pop(); 59 q.push(1); 60 memset(ans,0,sizeof(ans)); 61 k=b=0; 62 while (!q.empty()) 63 { 64 n1=a[q.front()]; 65 q.pop(); 66 if (!n1.b) 67 { 68 b=1; 69 break; 70 } 71 ans[++k]=n1.val; 72 if (n1.lch) q.push(n1.lch); 73 if (n1.rch) q.push(n1.rch); 74 } 75 if (b) 76 printf("not complete\n"); 77 else 78 { 79 printf("%d",ans[1]); 80 for (i=2;i<=k;i++) 81 printf(" %d",ans[i]); 82 printf("\n"); 83 } 84 } 85 }
如果直接用数组下标表示位置,那么当所有节点连成一条线的时候下标将变得很大。所以需要在每个节点记录他的左右儿子位置,这样可以节省空出来的空间。
每个节点用一个bool记录是否被赋过值,如果没被赋过值或是被赋第二次值,那就not complete了。
但是注意的细节就是由于多组数据,即使读入时已经知道not complete也要读完。