https://pintia.cn/problem-sets/994805046380707840/problems/994805070971912192
本题目是一道涉及二叉搜索树、树的遍历的裸题,模拟即可,可以建树,也可不建。
贴个代码:
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <map>
#include <cstdio>
#include <set>
#define LL long long;
#define INF 0x3f3f3f3f
using namespace std;
const int maxn=10005;
int n,a[maxn],cnt;
typedef struct node
{
int data;
struct node *l,*r;
}tree;
bool check1(int h,int r)
{
if(h>=r)
return true;
int i,j;
for(i=h+1;i<=r;i++)
{
if(a[i]>=a[h])
{
break;
}
}
for(j=i+1;j<=r;j++)
{
if(a[j]<a[h])
{
return false;
}
}
return check1(h+1,i-1)&&check1(i,r);
}
bool check2(int h,int r)
{
if(h>=r) return true;
int i,j;
for(i=h+1;i<=r;i++)
{
if(a[i]<a[h])
{
break;
}
}
for(j=i+1;j<=r;j++)
{
if(a[j]>=a[h])
{
return false;
}
}
return check2(h+1,i-1)&&check2(i,r);
}
void print1(int h,int r)
{
int i,j;
if(h>r)
return ;
if(h==r)
{
cnt++;
if(cnt==1)
cout << a[h];
else
cout << ' ' << a[h];
return ;
}
for(i=h+1;i<=r;i++)
{
if(a[i]>=a[h])
{
break;
}
}
print1(h+1,i-1);
print1(i,r);
cout << ' ' << a[h];
}
void print2(int h,int r)
{
int i,j;
if(h>r)
return ;
if(h==r)
{
cnt++;
if(cnt==1)
cout << a[h];
else
cout << ' ' << a[h];
return ;
}
for(i=h+1;i<=r;i++)
{
if(a[i]<a[h])
{
break;
}
}
print2(h+1,i-1);
print2(i,r);
cout << ' ' << a[h];
}
tree* build(int h,int r)
{
if(h>r)
return NULL;
if(h==r)
{
tree* t=(tree*)malloc(sizeof(node));
t->data=a[h];
t->l=NULL;
t->r=NULL;
return t;
}
int i;
for(i=h+1;i<=r;i++)
{
if(a[i]>=a[h])
{
break;
}
}
tree* t=(tree*)malloc(sizeof(node));
t->data=a[h];
t->l=build(h+1,i-1);
t->r=build(i,r);
return t;
}
void pre(tree *t)
{
if(t==NULL)
return ;
pre(t->l);
pre(t->r);
cnt++;
if(cnt==1)
{
cout << t->data;
}
else
cout << ' ' << t->data;
}
tree* build2(int h,int r)
{
if(h>r)
return NULL;
if(h==r)
{
tree* t=(tree*)malloc(sizeof(node));
t->data=a[h];
t->l=NULL;
t->r=NULL;
return t;
}
int i;
for(i=h+1;i<=r;i++)
{
if(a[i]<a[h])
{
break;
}
}
tree* t=(tree*)malloc(sizeof(node));
t->data=a[h];
t->l=build2(h+1,i-1);
t->r=build2(i,r);
return t;
}
int main()
{
//ios::sync_with_stdio(false);
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
if(check1(0,n-1))
{
cout << "YES\n";
cnt=0;
//print1(0,n-1);
tree *h=build(0,n-1);
pre(h);
}
else if(check2(0,n-1))
{
cout << "YES\n";
cnt=0;
//print2(0,n-1);
tree *h=build2(0,n-1);
pre(h);
}
else
cout << "NO\n";
return 0;
}