Topic:
An inorder binary tree traversal can is implemented in a non-recursive to a stack with a. 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
Analysis: The main is to create a binary tree based on the input, and then the subsequent traversal
Code:
#pragmaMark-tree traversals Again#include<stdio.h>typedefstructTraversaltreenode {intvalue; structTraversaltreenode *Left ; structTraversaltreenode *Right ;} Traversaltreenode;intFlag; Traversaltreenode*createtraversaltreenode (intvalue) {Traversaltreenode*node = (Traversaltreenode *)malloc(sizeof(Traversaltreenode)); Node->value =value; Node->left =NULL; Node->right =NULL; returnnode;}voidPostordertraversal (Traversaltreenode *head) { if(head) {postordertraversal (head)-Left ); Postordertraversal (Head-Right ); if(Flag = =0) {printf ("%d", head->value); Flag=1; } Else{printf ("%d", head->value); } }}intMain () {intNodenum =0; scanf ("%d", &nodenum); intOperationcount =2*Nodenum; Traversaltreenode*a[ -]; inttop =-1; //The first node is definitely a push intindex =-1; scanf ("%*s%d", &index); Traversaltreenode*head =Createtraversaltreenode (index); a[0] =Head; Top=0; Traversaltreenode*popitem =NULL; for(inti =1; i < Operationcount; i++) { intindex =-1; Charstr[4]; scanf ("%s", str); unsignedLongLen =strlen (str); if(Len >=4) {scanf ("%d", &index); Traversaltreenode*newnode =Createtraversaltreenode (index); if(popitem) {if(!popitem->Left ) {Popitem->left =NewNode; } Else{Popitem->right =NewNode; } } Else { if(!a[top]->Left ) {A[top]->left =NewNode; } Else{A[top]->right =NewNode; }} Top++; A[top]=NewNode; Popitem=NULL; } Else{Popitem=A[top]; A[top]=NULL; Top--; }} Flag=0; Postordertraversal (head);}
Operation Result:
PAT006 Tree traversals Again