The title is as follows: Given a sequence of binary trees, you is 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 has fewer than .
In a level-order traversal of a tree, the data in all nodes at a given level is printed in left-to-right order a nd all nodes at level K is 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 was specified by a sequence of pairs (n,s) where n was the value at The node whose path from the root was given by the string s. A path is given a sequence of l' s and R's where l indicates a left branch and R Ind Icates a right branch. In the tree diagrammed above, the node containing are specified by (13,RL), and the node containing 2 are 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 being completely specified if every node on all root-to-node paths in the tree is GIV En a value exactly once.
1#include <cstdio>2#include <cstring>3#include <queue>4 using namespacestd;5 structnode6 {7 intLch,rch,val;8 BOOLb;9}a[260],n1,n2;Ten intn,ans[260]; One intRd () A { - intI,j,k,p,x,y,z,rt; - Chars[ -],c1,c2; theMemset (A,0,sizeof(a)); -n=1; - if(SCANF ("%s", s) ==-1)return 0; -rt=1; + while(1) - { + if(s[1]==')') Break; Ax=0; at for(i=1; s[i]!=','; i++) -x=x*Ten+s[i]-'0'; -p=1; - for(i=i+1; I<=strlen (s)-2; i++) - if(s[i]=='L') - { in if(!a[p].lch) a[p].lch=++N; -p=A[p].lch; to } + Else - { the if(!a[p].rch) a[p].rch=++N; *p=A[p].rch; $ }Panax Notoginseng if(a[p].b) rt=-1; -A[p].val=x; thea[p].b=1; +scanf"%s", s); A } the returnRT; + } -queue<int>Q; $ intMain () $ { - inti,j,k,l,m,p,x,y,z; - BOOLb; the while(1) - {Wuyix=Rd (); the if(!x) Break; - if(x==-1) Wu { -printf"Not complete\n"); About Continue; $ } - while(!q.empty ()) Q.pop (); -Q.push (1); -memset (ans,0,sizeof(ans)); Ak=b=0; + while(!q.empty ()) the { -n1=A[q.front ()]; $ Q.pop (); the if(!n1.b) the { theb=1; the Break; - } inans[++k]=N1.val; the if(N1.lch) Q.push (N1.lch); the if(N1.rch) Q.push (n1.rch); About } the if(b) theprintf"Not complete\n"); the Else + { -printf"%d", ans[1]); the for(i=2; i<=k;i++)Bayiprintf"%d", Ans[i]); theprintf"\ n"); the } - } -}
If the position is represented directly by an array subscript, the subscript will become large when all nodes are connected to a line. So it is necessary to record his left and right son position at each node, so as to save space.
Each node is assigned a value with a bool record, and if it is not assigned a value or is assigned a second value, it is not complete.
But the attention to detail is due to multiple sets of data, even if the read-in has been known not to complete also read.
UVA 122 trees on the LEVEL--YHX