【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];
这样同样正确

AAAAAccepted code:

 1 #define HAVE_STRUCT_TIMESPEC
 2 #include<bits/stdc++.h>
 3 using namespace std;
 4 int pre[1007];
 5 vector<int>post;
 6 int flag;
 7 void dfs(int l,int r){
 8     if(l>r)
 9         return ;
10     int ll=l+1,rr=r;
11     if(!flag){
12         while(ll<=r&&pre[ll]<pre[l])
13             ++ll;
14         while(rr>l&&pre[rr]>=pre[l])
15             --rr;
16     }
17     else{
18         while(ll<=r&&pre[ll]>=pre[l])
19             ++ll;
20         while(rr>l&&pre[rr]<pre[l])
21             --rr;
22     }
23     if(ll!=rr+1)
24         return ;
25     dfs(l+1,rr);
26     dfs(ll,r);
27     post.push_back(pre[l]);
28 }
29 int main(){
30     int n;
31     cin>>n;
32     for(int i=1;i<=n;++i)
33         cin>>pre[i];
34     flag=0;
35     dfs(1,n);
36     if(post.size()<n){
37         flag=1;
38         post.clear();
39         dfs(1,n);
40     }
41     if(post.size()<n)
42         cout<<"NO";
43     else{
44         cout<<"YES
";
45         cout<<post[0];
46         for(int i=1;i<post.size();++i)
47             cout<<" "<<post[i];
48     }
49     return 0;
50 }
保持热爱 不懈努力 不试试看怎么知道会失败呢(划掉) 世上无难事 只要肯放弃(划掉)
原文地址:https://www.cnblogs.com/ldudxy/p/11605680.html