C++之代码判断是否为完全二叉树

该代码示例展示了使用C++实现二叉树结构以及相关操作,包括初始化队列、判断队列满和空、入队、出队。此外,还定义了一个函数用于创建二叉树,并通过队列进行层次遍历,检查树的结构特性。
摘要由CSDN通过智能技术生成

原理条件在c++注意点专栏里 可以去看

#include <stdio.h>
#include <malloc.h>
typedef struct lk
{
    int data;
    struct lk *lchild;
    struct lk *rchild;
}bittree;
typedef struct kl
{
    int head;
    int tail;
    int size;
    bittree **data;
}queue;

void init(queue *queue,int size)
{
    queue->head = -1;
    queue->tail = -1;
    queue->size = size;
    queue->data = (bittree**)malloc(size *sizeof(bittree*));
    for(int i = 0 ; i < size ; i++)
    {
        queue->data[i] = NULL;
    }
}

//判满
int isfull(queue *queue)
{
    return (queue->tail + 1)%queue->size == queue->head;

//判空
int isempty(queue *queue)
{
    return queue->head == queue->tail;
}
 
//入队
void add(queue *queue,bittree *root)
{
    queue->tail = (queue->tail + 1 ) % queue->size;
    queue->data[queue->tail] = root;    
}

//出队 
bittree *out(queue *queue)
{
    if(isempty(queue)) return NULL;
    queue->head = (queue->head + 1 ) % queue->size;
    return queue->data[queue->head];
}

bittree *create()
{
    bittree *root = NULL;
    int num;
    scanf("%d",&num);
    if(num>0)
    {
        root = (bittree*)malloc(sizeof(bittree));
        root->data = num;
        root->lchild = create();
        root->rchild = create();
    }
}


//是 返回1  不是 返回55 
int iser(bittree *root)
{
    if(root == NULL) return 1;
    
    int count = 1;
    queue queue;
    init(&queue,50);
    add(&queue,root);
    
    while(!isempty(&queue))
    {
        root = out(&queue);
//        printf("%5d",root->data);
        if(root->lchild!=NULL)
        {
            add(&queue,root->lchild);
//            count++;
        }
        if(root->rchild!=NULL) 
        {
            add(&queue,root->rchild) ;
//            count++;
        }
        
        if(root->lchild==NULL && root->rchild!=NULL) return 55;
        if(root->lchild==NULL && root->rchild==NULL) 
        {
            while(!isempty(&queue))
            {
                root = out(&queue);
                if(root->lchild!=NULL||root->rchild!=NULL) return 55;
            }
        }
    }
    if (isempty(&queue)) return 1;
    else return 55;
//    printf("\n");
//    printf("%5d", count);
}


int main()
{
    bittree *root = create();
    printf("%5d",iser(root));
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值