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.
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
Through observation, it can be found that this question actually gives the pre-order and middle-order traversal of the binary tree, and then outputs the post-order traversal of the binary tree. The test sample has been unable to pass, and later found to be ni-1, not n-i+1, pay attention to the change of the subscript each time it recurs.
Note: bef stands for before (beginning of the preamble), mid stands for in (beginning in the middle sequence), and aft stands for after (beginning of the post sequence). pre-order traversal, in-order traversal, post-order traversal
#include <iostream>
#include <stack>
using namespace std;
int pre[35],in[35],post[35];
void order(int bef,int mid,int aft,int n){
if(n<1)
return;
if(n==1)//递归终止条件
post[aft] = pre[bef];
else{
int tmp = pre[bef];
post[aft+n-1] = tmp;
int i;
for(i = 0;i<n;i++){
if(in[mid+i]==tmp)
break;
}
order(bef+1,mid,aft,i);
order(bef+i+1,mid+i+1,aft+i,n-i-1);
}
}
void print(int n){
if(n<1)
return;
cout << post[0];
for(int i = 1;i<n;i++)
cout << " " << post[i];
}
int main(){
int n,x,m;
cin >> n;
stack<int> s;
int k = 0,p = 0;
string op;
//注意是2*n,因为n个结点的中序遍历对应2*n次出栈和入栈
for(int i = 0;i<2*n;i++){
cin >> op;
if(op=="Push"){
cin >> x;
pre[k++] = x;
s.push(x);
}
else if(op=="Pop"&&!s.empty()){
m = s.top();
s.pop();
in[p++] = m;
}
}
order(0,0,0,n);
print(n);
return 0;
}