PTA上的题 :是否完全二叉搜索树 (30分)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>

struct node
{
    int data, num;
    struct node *l, *r;
} * q[100];
struct node *root = NULL;

struct node *buildtree(struct node *root, int x)
{
    if (root == NULL)
    {
        root = (struct node *)malloc(sizeof(struct node));
        root->data = x;
        root->l = NULL;
        root->r = NULL;
    }
    else if (x > root->data)
        root->l = buildtree(root->l, x);
    else
        root->r = buildtree(root->r, x);
    return root;
}
int main()
{
    int n;
    scanf("%d", &n);
    int i;
    for (i = 0; i < n; i++)
    {
        int x;
        scanf("%d", &x);
        root = buildtree(root, x);
    }
    int flag = 1;
    int a[100], cnt = 0;
    int head = 0, tail = 0;
    if (root != NULL)
    {
        q[tail] = root;
        q[tail++]->num = 1;
        while (head < tail)
        {
            struct node *t = q[head];
            if (t->num > n)
                flag = 0;
            if (t->l)
            {
                t -> l -> num = t -> num * 2;
                q[tail++] = t->l;
            }
            if (t->r)
            {
                t -> r -> num = t -> num * 2 + 1;
                q[tail++] = t->r;
            }
            a[cnt++] = q[head++]->data;
        }
    }
    for (i = 0; i < cnt; i++)
        printf("%d%c", a[i], i == cnt - 1 ? '\n' : ' ');
    if (flag)
        printf("YES\n");
    else
        printf("NO\n");
    return 0;
}

mmp
自己调试了一天的时间(maybe)终于给弄出来了,总结一下自己出现的错误。
1,补题的编译器只有gcc,所以用c写了代码,但是c的太多东西不一样,比如malloc忘记了,不能用node root之类的,应该用struct node root,还有,c没有stl库,所以队列不能用,必须自己创建。
2.most importantly !!! 自己将队列的队列的num值改变了,但是,二叉树没改变,到最后,都不明白哪里错了。。。。。。
3两个if语句中的tail是会改变的所以根节点也会变!!!!!!!

参考:https://blog.csdn.net/LMengi000/article/details/79616579?utm_source=blogxgwz6

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值