【PAT甲级】1086 Tree Traversals Again (25 分)(树知二求一)

六月ゝ 毕业季﹏ 提交于 2019-12-04 19:19:22

题意:
输入一个正整数N(<=30),接着输入2*N行表示栈的出入(入栈顺序表示了二叉搜索树的先序序列,出栈顺序表示了二叉搜索树的中序序列),输出后序序列。

代码:

#define HAVE_STRUCT_TIMESPEC
#include<bits/stdc++.h>
using namespace std;
stack<int>st;
int a[37],b[37];
int ans[37];
void build(int n,int*a,int*b,int*ans){
if(!n)
return ;
int x=find(b,b+n,a[0])-b;
build(x,a+1,b,ans);
build(n-x-1,a+x+1,b+x+1,ans+x);
ans[n-1]=a[0];
}
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin>>n;
int cnt1=0,cnt2=0;
for(int i=1;i<=n+n;++i){
string s;
cin>>s;
int x;
if(s[1]=='u')
cin>>x;
if(s[1]=='u'){
a[cnt1++]=x;
st.push(x);
}
else{
b[cnt2++]=st.top();
st.pop();
}
}
build(n,a,b,ans);
for(int i=0;i<n;++i){
cout<<ans[i];
if(i<n-1)
cout<<" ";
}
return 0;
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!