转为已知先序和中序求后序
push的顺序是先序
pop的顺序是后序
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<string>
#include<stack>
#include<vector>
using namespace std;
vector<int> in,pre,post;
struct node{
int data;
node* lchild;
node* rchild;
};
node* create(int preL,int preR,int inL,int inR){
if(preL>preR){
return NULL;
}
node* root = new node;
int k;
for(k=inL;k<=inR;k++){
if(in[k]==pre[preL]) break;
}
root->data=in[k];
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;
}
void postttvl(node* root){
if(root->lchild!=NULL) postttvl(root->lchild);
if(root->rchild!=NULL) postttvl(root->rchild);
post.push_back(root->data);
}
int main(){
int n;
stack<int> st;
scanf("%d",&n);
int i,index;
string method;
while(in.size()!=n){
cin>>method;
if(method=="Push"){
scanf("%d",&index);
st.push(index);
pre.push_back(index);
}
else if(method=="Pop"){
in.push_back(st.top());
st.pop();
}
}
node* root=create(0,n-1,0,n-1);
postttvl(root);
for(i=0;i<n;i++){
if(i<n-1) printf("%d ",post[i]);
else printf("%d\n",post[i]);
}
system("pause");
return 0;
}
PAT A1086 tree traversals again(25)
最新推荐文章于 2022-11-28 20:01:59 发布