(Sequence preorder traversal is determined whether the traverse and outputs BST) [PAT] Grade 1043 Is It a Binary Search Tree (25 minutes)

Meaning of the questions:

Enter a positive integer N (<= 1000), the next number N input points. If the input is just a sequence of binary search tree or its mirror image (the central inverted 180 °) preorder traversal, then the YES output, and its output postorder, otherwise the output NO.

trick:

for(auto it:post)
cout<<it<<((it!=post[n-1])?" ":"");

So that the output data point will make 0,1 malformed. . . Reason unknown

 

cout<<post[0];
for(int i=1;i<post.size();++i)
cout<<" "<<post[i];
This is also true

 

Code:

#define HAVE_STRUCT_TIMESPEC
#include<bits/stdc++.h>
using namespace std;
int pre[1007];
vector<int>post;
int flag;
void dfs(int l,int r){
if(l>r)
return ;
int ll=l+1,rr=r;
if(!flag){
while(ll<=r&&pre[ll]<pre[l])
++ll;
while(rr>l&&pre[rr]>=pre[l])
--rr;
}
else{
while(ll<=r&&pre[ll]>=pre[l])
++ll;
while(rr>l&&pre[rr]<pre[l])
--rr;
}
if(ll!=rr+1)
return ;
dfs(l+1,rr);
dfs(ll,r);
post.push_back(pre[l]);
}
int main(){
int n;
cin>>n;
for(int i=1;i<=n;++i)
cin>>pre[i];
flag=0;
dfs(1,n);
if(post.size()<n){
flag=1;
post.clear();
dfs(1,n);
}
if(post.size()<n)
cout<<"NO";
else{
cout<<"YES\n"<<post[0];
for(int i=1;i<post.size();++i)
cout<<" "<<post[i];
}
return 0;
}

Guess you like

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