zoukankan      html  css  js  c++  java
  • 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
    %d",post[0]);
    38         for(int i=1;i<n;++i)
    39             printf(" %d",post[i]);
    40         printf("
    ");
    41     }
    42     else
    43         printf("NO
    ");
    44     return 0;
    45 }
  • 相关阅读:
    jquery笔记
    css选择器
    Linq 巧用 Max,Sum
    Linq Aggregate
    Linq 对象的比较 Contains,Max
    Linq SelectMany 交叉连接
    JQ 标签相关知识
    C# HttpClient设置cookies的两种办法 (转发)
    使用 HttpClient 请求 Web Api
    MySQL 避免重复数据的批量插入与批量更新
  • 原文地址:https://www.cnblogs.com/FrankChen831X/p/10541785.html
Copyright © 2011-2022 走看看