L2-004 这是二叉搜索树吗?

发布时间:2019年11月12日 阅读:298 次

https://pintia.cn/problem-sets/994805046380707840/problems/99480507097191219

                                 

                                                 L2-004 这是二叉搜索树吗? (25 分)

一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点,

  • 其左子树中所有结点的键值小于该结点的键值;

  • 其右子树中所有结点的键值大于等于该结点的键值;

  • 其左右子树都是二叉搜索树。

所谓二叉搜索树的“镜像”,即将所有结点的左右子树对换位置后所得到的树。

给定一个整数键值序列,现请你编写程序,判断这是否是对一棵二叉搜索树或其镜像进行前序遍历的结果。

输入格式:

输入的第一行给出正整数 )。随后一行给出  个整数键值,其间以空格分隔。

输出格式:

如果输入序列是对一棵二叉搜索树或其镜像进行前序遍历的结果,则首先在一行中输出 YES ,然后在下一行输出该树后序遍历的结果。数字间有 1 个空格,一行的首尾不得有多余空格。若答案是否,则输出 NO

输入样例 1:

7
8 6 5 7 10 8 11

输出样例 1:

YES
5 7 6 8 11 10 8

输入样例 2:

7
8 10 11 8 6 7 5

输出样例 2:

YES
11 8 10 7 5 6 8

输入样例 3:

7
8 6 8 5 10 9 11

输出样例 3:

NO
作者: 陈越
单位: 浙江大学
时间限制: 400 ms
内存限制: 64 MB
#include<bits/stdc++.h>
#define ll long long int
#define mod 998244353
using namespace std;
int a[2000];
struct node*root = NULL;
struct node
{
    int data;
    struct node*l;
    struct node*r;
};
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* build(struct node*t,int key)
{
    if(t==NULL)
    {
        node* p = new node;
        p->data = key;
        p->l = NULL;
        p->r = NULL;
        return p;
    }
    if(key>=t->data)
        t->r = build(t->r,key);
    else
        t->l = build(t->l,key);
    return t;
}
struct node* build2(struct node*t,int key)
{
    if(t==NULL)
    {
        node* p = new node;
        p->data = key;
        p->l = NULL;
        p->r = NULL;
        return p;
    }
    if(key<t->data)
        t->r = build2(t->r,key);
    else
        t->l = build2(t->l,key);
    return t;

}
void print(struct node*t)
{
    if(!t)
        return ;
    print(t->l);
    print(t->r);
    if(t!=root)
        printf("%d ",t->data);
}

int main()
{
// ios::sync_with_stdio(false);
    int n;
    cin>>n;
    for(int i=0; i<n; i++)
    {
        cin>>a[i];
    }
    int flag1 = check1(0,n-1);
    int flag2 = check2(0,n-1);
    if(!flag1&&!flag2)
    {
        printf("NO\n");
        return 0;
    }

    if(!flag1)
        for(int i=0; i<n; i++)
            root = build2(root,a[i]);
    else
        for(int i=0; i<n; i++)
            root = build(root,a[i]);
    printf("YES\n");
    print(root);
    printf("%d\n",root->data);
    return 0;
}


Tag:
相关文章

发表评论: