[PAT] Grade 1086 Tree Traversals Again (25 minutes) (seeking a two-known tree)

The meaning of problems:
enter a positive integer N (<= 30), followed by row 2 * N denotes the input stack access (Drawing shows a sequence of first order of the sequence of binary search tree, the order of the stack shows a binary search tree motif sequence), and outputs the serial sequence.

Code:

#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;
}

Guess you like

Origin www.cnblogs.com/ldudxy/p/11879678.html