PAT (Advanced Level) 1043. Is It a Binary Search Tree (25)

简单题。构造出二叉搜索树,然后check一下。

#include<stdio.h>
#include<algorithm>
using namespace std;

const int maxn=100000+10;
struct Node
{
    int left;
    int right;
    int val;
} s[maxn];

int n;
int a[maxn];
int ans[maxn],tot;
int h[maxn];
int k;

void dfs(int x)
{
    ans[k++]=s[x].val;
    if(s[x].left!=-1) dfs(s[x].left);
    if(s[x].right!=-1) dfs(s[x].right);
}

void houxu(int x)
{
    if(s[x].left!=-1) houxu(s[x].left);
    if(s[x].right!=-1) houxu(s[x].right);
    h[k++]=s[x].val;
}

bool check()
{
    for(int i=0;i<n;i++) if(ans[i]!=a[i]) return 0;
    return 1;
}

int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=0; i<n; i++) scanf("%d",&a[i]);
        for(int i=0; i<=n; i++) s[i].left=s[i].right=-1;
        int id=0;
        s[id++].val=a[0];
        for(int i=1; i<n; i++)
        {
            int now=0;
            while(1)
            {
                if(a[i]<s[now].val)
                {
                    if(s[now].left!=-1) now=s[now].left;
                    else
                    {
                        s[now].left=id;
                        s[id++].val=a[i];
                        break;
                    }
                }
                else
                {
                    if(s[now].right!=-1) now=s[now].right;
                    else
                    {
                        s[now].right=id;
                        s[id++].val=a[i];
                        break;
                    }
                }
            }
        }

       // for(int i=0;i<id;i++) printf("%d %d %d\n",s[i].val,s[i].left,s[i].right);

        k=0;
        dfs(0);
        if(check()==1)
        {
            printf("YES\n");
            k=0; houxu(0);
            for(int i=0;i<n;i++)
            {
                printf("%d",h[i]);
                if(i<n-1) printf(" ");
                else printf("\n");
            }
            continue;
        }

        k=0;
        for(int i=0;i<n;i++) swap(s[i].left,s[i].right);
        dfs(0);
        if(check()==1)
        {
            printf("YES\n");
            k=0; houxu(0);
            for(int i=0;i<n;i++)
            {
                printf("%d",h[i]);
                if(i<n-1) printf(" ");
                else printf("\n");
            }
            continue;
        }

        printf("NO\n");

    }
    return 0;
}

 

转载于:https://www.cnblogs.com/zufezzt/p/5526916.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值