pta l2-4(这是二叉搜索树吗?)

题目链接:https://pintia.cn/problem-sets/994805046380707840/problems/994805070971912192

题意:给定n以及n个整数,问该序列是否为二叉搜索树的前序遍历或者二叉搜索树镜像的前序遍历,若是,则输出YES,并输出其后序遍历,否则输出NO。

思路:先判断是否为二叉搜索树的前序遍历,令is=false,通过递归和二叉搜索树的性质计算其后序遍历序列,若序列长度等于n,即成立,否则令is=true,再次计算其后序遍历序列,若序列长度为n即成立,否则输出“NO”。

AC代码:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 int n;
 5 vector<int> pre,post;
 6 bool is;
 7 
 8 void getpost(int l,int r){
 9     int i=l+1,j=r;
10     if(l>r) return;
11     if(!is){
12         while(i<=r&&pre[i]<pre[l]) ++i;
13         while(j>l&&pre[j]>=pre[l]) --j;
14     }
15     else{
16         while(i<=r&&pre[i]>=pre[l]) ++i;
17         while(j>l&&pre[j]<pre[l]) --j;
18     }
19     if(i-j!=1) return;
20     getpost(l+1,j);
21     getpost(i,r);
22     post.push_back(pre[l]);
23 }
24 
25 int main(){
26     scanf("%d",&n);
27     pre.resize(n);
28     for(int i=0;i<n;++i)
29         scanf("%d",&pre[i]);
30     getpost(0,n-1);
31     if(post.size()!=n){
32         is=true;
33         post.clear();
34         getpost(0,n-1);
35     }
36     if(post.size()==n){
37         printf("YES\n%d",post[0]);
38         for(int i=1;i<n;++i)
39             printf(" %d",post[i]);
40         printf("\n");
41     }
42     else
43         printf("NO\n");
44     return 0;
45 }

猜你喜欢

转载自www.cnblogs.com/FrankChen831X/p/10541785.html