03-3. Tree traversals Again (+) an inorder binary Tree traversal can being implemented in a non-recursive-a-type with a stack. For example, suppose if a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operation s Are:push (1); Push (2); Push (3); Pop (); Pop (); Push (4); Pop (); Pop (); Push (5); Push (6); Pop (); Pop (). Then a the unique binary tree (shown in Figure 1) can is generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.
Figure 1
Input Specification:
Each input file contains the one test case. The first line contains a positive integer N (<=30) which was the total number of nodes in a tree (and he nCE the nodes is numbered from 1 to N). Then 2N lines follow, each describes a stacks operation in the format: "Push X" where x is the index of the node being Push Ed onto the stack; or "pop" meaning to pops one node from the stack.
Output Specification:
For each test case, print the Postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must is separated by exactly one space, and there must is no extra space at the end of the line.
Sample Input:
6Push 1Push 2Push 3PopPopPush 4PopPopPush 5Push 6PopPop
Sample Output:
3 4 2 6 5 1
#include <stdio.h>#defineMaxSize 35#defineEmpty_tos (-1)#definePUSH 1#definePOP 2typedefstructstack_record{intTop_of_stack; intstack_array[maxsize];} Stack;voidInit_stack (Stack *S) {S->top_of_stack=Empty_tos;}intIs_empty (Stack*R) { return(s->top_of_stack==empty_tos);}intIs_full (Stack*R) { return(s->top_of_stack==maxsize-1); }voidPush (intX,stack *S) { if(Is_full (S))return; ElseS->stack_array[++s->top_of_stack]=x;}intTop (Stack*R) { if(!Is_empty (S))returnS->stack_array[s->top_of_stack];}intPop (Stack*R) { if(Is_empty (S))return; Else returns->stack_array[s->top_of_stack--]; }intMain () {Stack s1,s2; intoparray[2*maxsize+1][2]={-1}; Chartmpstr[ -],tmp[ -],tmp1[ -]; Init_stack (&S1); Init_stack (&S2); intI,nodenum,tmppop,tmppop1; intprinttag=0; scanf ("%d",&nodenum); GetChar (); for(i=0;i<2*nodenum;i++) {gets (TMPSTR); if(tmpstr[1]=='u') {sscanf (TMPSTR,"%s%s", TMP,TMP1); oparray[i][0]=PUSH; oparray[i][1]=atoi (TMP1); }Else{oparray[i][0]=POP; } } for(i=0;i<2*nodenum;i++){ if(oparray[i][0]==push) push (oparray[i][1],&S1); Else{ if(oparray[i+1][0]==PUSH) { if(Top (&S1) ==-1) {push (Oparray[i+1][1],&S2); }Else{push (-1,&S2); Push (Pop (&S1),&S2); Push (-1,&S1); Push (Oparray[i+1][1],&S2); } I++; } Else{Tmppop=pop (&S1); if(tmppop==-1){ while((Tmppop1=pop (&S2))!=-1) printf ("%d", TMPPOP1); }Else{ if(!PrintTag) {printf ("%d", Tmppop); PrintTag++; }Elseprintf ("%d", Tmppop); } } } } return 0;}View Code
03-3. Tree traversals Again (25)