思路:对于一颗合法的二叉搜索树,那么即满足对于区间[l,r],存在一个点i,a[l]<a[i]<a[r],那么就区间递归下去判断就可以了
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 1005;
int a[maxn];
int check1(int l,int r)
{
if(l>=r)
return 1;
int key = r;
for(int i = l+1;i<=r;i++)
if(a[l]<=a[i])
{
key = i;
break;
}
for(int i = key+1;i<=r;i++)
if(a[l]>a[i])
return 0;
return check1(l+1,key-1)&&check1(key,r);
}
int check2(int l,int r)
{
if(l>=r)
return 1;
int key = r;
for(int i = l+1;i<=r;i++)
if(a[l]>=a[i])
{
key = i;
break;
}
for(int i = key+1;i<=r;i++)
if(a[l]<a[i])
return 0;
return check2(l+1,key-1)&&check2(key,r);
}
struct Node
{
int val;
Node *lchild;
Node *rchild;
};
Node *root = NULL;
Node* build(Node *t,int key)
{
if(t==NULL)
{
Node*p = new Node;
p->val = key;
p->lchild = NULL;
p->rchild = NULL;
return p;
}
if(key >= t->val)
t->rchild = build(t->rchild,key);
else
t->lchild = build(t->lchild,key);
return t;
}
Node* rbuild(Node *t,int key)
{
if(t==NULL)
{
Node*p = new Node;
p->val = key;
p->lchild = NULL;
p->rchild = NULL;
return p;
}
if(key < t->val)
t->rchild = rbuild(t->rchild,key);
else
t->lchild = rbuild(t->lchild,key);
return t;
}
void print(Node *t)
{
if(t==NULL)
return;
print(t->lchild);
print(t->rchild);
if(t!=root)
printf("%d ",t->val);
}
int main()
{
int n;
scanf("%d",&n);
for(int i = 0;i<n;i++)
scanf("%d",&a[i]);
int flag1 = check1(0,n-1);
int flag2 = check2(0,n-1);
if(!(flag1||flag2))
{
printf("NO\n");
return 0;
}
else if (flag1)
for(int i = 0;i<n;i++)
root = build(root,a[i]);
else if (flag2)
for(int i = 0;i<n;i++)
root = rbuild(root,a[i]);
printf("YES\n");
print(root);
printf("%d"