An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be 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 one test case. For each case, the first line contains a positive integer N (≤30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: "Push X" where X is the index of the node being pushed onto the stack; or "Pop" meaning to pop 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 be separated by exactly one space, and there must be 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
http://pta.patest.cn/pta/test/16/exam/4/question/667
// 5-5 Tree Traversals Again (25分)
// http://pta.patest.cn/pta/test/16/exam/4/question/667
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <iterator>
using namespace std ;
#define INF 999999
#define N 33
int n;
typedef struct node{
int data ;
struct node* left ;
struct node* right ;
node(int _data)
{
data = _data ;
left = NULL ;
right = NULL ;
}
}Bnode ;
int pre[N] ;
int in[N] ;
Bnode* createTree(int preL , int preR ,int inL , int inR)
{
if(inL > inR)
return NULL ;
int data = pre[preL] ;
Bnode* r = new node(data) ;
int pos = 0 ;
while(in[pos++] != data);
pos -- ;
// 1 2 3 4 5 6 pre
// 3 2 4 1 6 5 in
r->left = createTree(preL + 1, preL + pos - inL , inL , pos - 1) ;
r->right = createTree(preL + pos - inL + 1, preR , pos + 1, inR) ;
return r ;
}
vector<int> post ;
void postOrder(Bnode* root)
{
if(root != NULL)
{
postOrder(root->left) ;
postOrder(root->right) ;
post.push_back(root->data) ;
}
}
int main()
{
//freopen("in.txt","r",stdin);
scanf("%d",&n) ;
stack<int> st ;
int i ,val ;
char s[10] ;
int prei = 0 ;
int ini = 0 ;
for(i = 0 ; i < 2*n; i ++)
{
scanf("%s" , s) ;
if(s[1] == 'u')
{
scanf("%d", &val);
pre[prei++] = val;
st.push(val);
}else{
int pval = st.top();
st.pop() ;
in[ini++] = pval ;
}
}
Bnode* root = createTree(0 , n-1 , 0 , n-1) ;
postOrder(root) ;
printf("%d",post[0]) ;
for(i = 1 ;i < n ; i ++)
{
printf(" %d" ,post[i]);
}
printf("\n");
return 0 ;
}