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

题意:
输入一个正整数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;
}

猜你喜欢

转载自www.cnblogs.com/ldudxy/p/11879678.html
今日推荐