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 PopSample Output:
3 4 2 6 5 1
push为前序,pop为中序。
#include<stdio.h>
#include<stdlib.h>
#include<stack>
using namespace std;
int qx[35],zx[35];
int cou1=0,cou2=0,flag=0;
typedef struct Node *node;
struct Node{
int x;
node left;
node right;
};
node build(int s1,int e1,int s2,int e2){
node T=(node)malloc(sizeof(struct Node));
T->x=qx[s1];
T->left=T->right=NULL;
int root,i;
for(i=s2;i<=e2;i++){
if(zx[i]==qx[s1]){
root=i;break;
}
}
if(root!=s2){
T->left=build(s1+1,root-s2+s1,s2,root-1);
}
if(root!=e2){
T->right=build(root-s2+s1+1,e1,root+1,e2);
}
return T;
}
void post(node T){
if(T){
post(T->left);
post(T->right);
if(flag==0){
printf("%d",T->x);flag=1;
}
else{
printf(" %d",T->x);
}
}
}
int main(){
int n,i,x;
char str[5];
scanf("%d",&n);
stack<int>s;
for(i=0;i<2*n;i++){
scanf("%s",str);
if(str[1]=='u'){
scanf("%d",&x);
qx[cou1++]=x;
s.push(x);
}
else{
zx[cou2++]=s.top();
s.pop();
}
}
node T=build(0,n-1,0,n-1);
post(T);
}