题目描述


分析:
入栈顺序为先序遍历顺序,出栈顺序为中序遍历顺序,即已知先序遍历和中序遍历,求后序遍历
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include<stack>
using namespace std;
struct node{
int data;
node* lchild;
node* rchild;
};
int pre[55],in[55],post[55];
int n;
node* create(int preL,int preR,int inL,int inR){
if(preL>preR){
return NULL;
}
node* root=new node;
root->data=pre[preL];
int k;
for(k=inL;k<=inR;k++){
if(in[k]==pre[preL]){
break;
}
}
int numLeft=k-inL;
root->lchild=create(preL+1,preL+numLeft,inL,k-1);
root->rchild=create(preL+numLeft+1,preR,k+1,inR);
return root;
}
int num=0;
void postorder(node* root){
if(root==NULL)
return;
postorder(root->lchild);
postorder(root->rchild);
printf("%d",root->data);
num++;
if(num<n) printf(" ");
}
int main(){
scanf("%d",&n);
char str[5];
int x,preIndex=0,inIndex=0;
stack<int>s;
for(int i=0;i<2*n;i++){
scanf("%s",str);
if(strcmp(str,"Push")==0){
scanf("%d",&x);
pre[preIndex++]=x;
s.push(x);
}
else{
in[inIndex++]=s.top();
s.pop();
}
}
node*root=create(0,n-1,0,n-1);
postorder(root);
return 0;
}