L2-4. 这是二叉搜索树吗? PAT

题目 https://www.patest.cn/contests/gplt/L2-4
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
int t[1005];
int N;
int tt[1005],flag;
int pp[1005],temp;
struct node{
    int n;
    struct node*left;
    struct node*right;
};

struct node* build(struct node* T,int nn)
{
    if(T==NULL){
        struct node*t =(struct node*) malloc(sizeof(struct node));
        if(t==NULL)return NULL;
        t->n=nn;
        t->left=NULL;
        t->right=NULL;
        return t;
    }
    if(nn>=T->n){
        T->right=build(T->right,nn);
    }
    else {
        T->left=build(T->left,nn);
    }
    return T;
};

struct node* build2(struct node*T,int nn)
{
    if(T==NULL){
        struct node*t =(struct node*) malloc(sizeof(struct node));
        if(t==NULL)return NULL;
        t->n=nn;
        t->left=NULL;
        t->right=NULL;
        return t;
    }
    if(nn<T->n){
        T->right=build2(T->right,nn);
    }
    else {
        T->left=build2(T->left,nn);
    }
    return T;
};

void pre(struct node*T)
{
    if(T==NULL){
        return ;
    }
     tt[flag]=T->n;
      flag++;
    pre(T->left);
    pre(T->right);
    pp[temp]=T->n;
    temp++;
    return ;
}


int main()
{
    struct node *T;
    struct node *T2;
    T=NULL;
    T2=NULL;
    scanf("%d",&N);
    if(N==0){
        return 0;
    }
    for(int i=0;i<N;i++){
        scanf("%d",&t[i]);
    }
    for(int i=0;i<N;i++){
        T=build(T,t[i]);
    }
    pre(T);
    int i;
    for(i=0;i<N;i++){
        if(t[i]==tt[i]){
            continue;
        }
        else{
            for(int j=0;j<N;j++){
                T2=build2(T2,t[j]);
            }
            flag=0;temp=0;
            pre(T2);
            int j;
            for( j=0;j<N;j++){
                if(t[j]==tt[j]){
                    continue;
                }
                else{
                    printf("NO\n");
                    break;
                }
            }
            if(j==N){
                printf("YES\n");
                printf("%d",pp[0]);
                for(j=1;j<N;j++){
                       printf(" %d",pp[j]);
                }
                break;
            }
            else{
                break;
            }
        }
    }
    if(i==N){
        printf("YES\n");
        printf("%d",pp[0]);
        for(int i=1;i<N;i++){
            printf(" %d",pp[i]);
        }
    }
}

你可能感兴趣的:(L2-4. 这是二叉搜索树吗? PAT)