PTAA-1043-Is It a Binary Search Tree (25)

题意:

给出二叉搜索树的要求,询问按要求建树,正常建树和镜像建树是否其一满足条件,如果满足就输出后序遍历

#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long LL;
int ansl[1005];
int ansr[1005];
int poster[1005];
int a[1005];
int p1=0,p2=0,b=0;
struct tree
{
    int data;
    tree *left,*right;
};
tree * Build(tree* t,int num)
{
    if(t==NULL)
    {
        t=new tree;
        t->left=NULL;
        t->right=NULL;
        t->data=num;
        return t;
    }
    if(t->data>num)
    {
        t->left=Build(t->left,num);
    }
    else
    {
        t->right=Build(t->right,num);
    }
    return t;
}
void pre1(tree *t)
{
    if(t==NULL)
        return ;
    p1++;
    ansl[p1]=t->data;
    pre1(t->left);
    pre1(t->right);
}
void pre2(tree *t)
{
    if(t==NULL)
        return ;
    p2++;
    ansr[p2]=t->data;
    pre2(t->right);
    pre2(t->left);

}
void B1(tree *t)
{
    if(t==NULL)
        return ;
    B1(t->left);
    B1(t->right);

    b++;
    poster[b]=t->data;
}

void B2(tree *t)
{
    if(t==NULL)
        return ;

    B2(t->right);
    B2(t->left);
     b++;
    poster[b]=t->data;
}
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    tree *T=NULL;
    for(int i=1;i<=n;i++)
        T=Build(T,a[i]);
    pre1(T);
    pre2(T);
    int f1,f2;
    f1=f2=0;
    for(int i=1;i<=n;i++)
    {
        if(ansl[i]!=a[i])
        {
            f1=1;
            break;
        }
    }

    for(int i=1;i<=n;i++)
    {
        if(ansr[i]!=a[i])
        {
            f2=1;
            break;
        }
    }

    if(f2==1&&f1==1)
    {
        cout<<"NO"<


你可能感兴趣的:(===数据结构===,PATA,acm)