Topic Information
1086. Tree traversals Again (+)
Time limit of MS
Memory Limit 65536 KB
Code length limit 16000 B
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:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
Sample Output:
3 4 2 6 5 1
Thinking of solving problems
Binary Tree Traversal transformation
AC Code
#include <cstdio>#include <stack>using namespace STD;intpreorder[ *], inorder[ *];intN, Preid =0, iNID =0, cnt =0;intGet () {Chars[Ten];scanf('%s ', s);if(s[1] ==' O ')return-1;intAscanf("%d", &a);returnA;}voidBuildintPreb,intPreeintInbintINE) {if(Preb > Pree)return;introot = Preorder[preb];intInroot = INB; while(Inorder[inroot]! = root) ++inroot; Build (preb+1, Preb+inroot-inb, INB, inroot-1); Build (preb+inroot-inb+1, Pree, inroot+1, INE);if(cnt++! =0)Putchar("');printf("%d", root);}intMain () {scanf("%d", &n); Stack<int>St for(inti =0; I < n2; ++i) {intA = Get ();if(A! =-1) {St.push (a); preorder[preid++] = A; }Else{inorder[inid++] = St.top (); St.pop (); }} Build (0, N-1,0, N-1);return 0;}
1086. Tree Traversals Again (25) "Binary Tree"--pat (Advanced level) practise