每次出树的题目我都白给,好不容易遇到一道我会写的简单题QAQ
#include<iostream>
#include<stack>
using namespace std;
const int N=100;
int qian[N],zhong[N];
int cnt1,cnt2;
int hou[N];
int cnt;
stack<int> zz;
void build(int qianl,int qianr,int zhongl,int zhongr){
if(zhongl>zhongr) return ;
int u=qian[qianl];//父节点
int k;
for(k=zhongl;k<=zhongr;k++) {
if(zhong[k]==u) break;
}//找到了父节点在中序遍历里的位置
build(qianl+1,qianl+1+(k-1-zhongl),zhongl,k-1);
build(qianl+1+(k-1-zhongl)+1,qianr,k+1,zhongr);
hou[cnt++]=u;
}
int main(){
int n;
cin>>n;
for(int i=0;i<2*n;i++){
string kk;
cin>>kk;
if(kk=="Push"){
int x;
cin>>x;
qian[cnt1++]=x;
zz.push(x);
}
else{
int x=zz.top();
zz.pop();
zhong[cnt2++]=x;
}
}
build(0,n-1,0,n-1);
// for(int i=0;i<n;i++) cout<<qian[i]<<' ';
// cout<<endl;
// for(int i=0;i<n;i++) cout<<zhong[i]<<' ';
cout<<hou[0];
for(int i=1;i<cnt;i++) cout<<' '<<hou[i];
}
//知道前序中序求后序