push的顺序即为先序遍历
pop的顺序为中序遍历
根据先序遍历和中序遍历求后序遍历
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>
#include<vector>
using namespace std;
stack<int> s1;
void PreAndIn(int inorder[],int preorder[],int n){
if(n == 0)
return ;
int root;
root = preorder[0];
int i;
for(i = 0;i<n;i++)
if(inorder[i] == root)
break;
s1.push(root);
PreAndIn(inorder + i+1,preorder + i+1,n-i-1);//右子树先递归,先进stack实现postorder
PreAndIn(inorder,preorder+1,i);
}
int main(){
int i,j,pp,ip;
char str[10];
int n,num;
int preorder[35],inorder[35];
//FILE *fp;
//fp = fopen("1.in","r");
fscanf(stdin,"%d",&n);
stack<int> s;
pp = ip = 0;
int count = 0;
while(count<n){
fscanf(stdin,"%s",str);
if(!strcmp(str,"Push")){
fscanf(stdin,"%d",&num);
preorder[pp++] = num;
s.push(num);
}
else {
num = s.top();
s.pop();
inorder[ip++] = num;
count++;
}
}
//for(i = 0;i<n;i++)
//printf("%d ",preorder[i]);
//printf("\n");
//for(i = 0;i<n;i++)
//printf("%d ",inorder[i]);
PreAndIn(inorder,preorder,n);
for(i = 0;i<n;i++){
printf("%d",s1.top());
s1.pop();
if(i == n-1)
printf("\n");
else printf(" ");
}
return 0;
}
460

被折叠的 条评论
为什么被折叠?



