【PAT甲级】1043 Is It a Binary Search Tree (25 分)(判断是否为BST的先序遍历并输出后序遍历)

题意:

输入一个正整数N(<=1000),接下来输入N个点的序号。如果刚才输入的序列是一颗二叉搜索树或它的镜像(中心翻转180°)的先序遍历,那么输出YES并输出它的后序遍历,否则输出NO。

trick:

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

这样输出会使第0,1数据点格式错误。。。原因未知

cout<<post[0];
for(int i=1;i<post.size();++i)
cout<<" "<<post[i];
这样同样正确

代码:

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

猜你喜欢

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