判断一棵树是否为完全二叉树(c语言版)

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

//ABH##I###
struct Node{
    char data;
    struct Node *lchild,*rchild;
};

struct Node* createBitree(){
    char ch;
    struct Node *t;
    scanf("%c",&ch);
    if(ch=='#') {
        t = NULL;
    }else{
        if(!(t = (struct Node*)malloc(sizeof(struct Node))))
           exit(-1);
        t->data = ch;
        t->lchild=createBitree();
        t->rchild=createBitree();
    }
    return t;
}//前序遍历建树

//返回0代表非完全,1代表是完全二叉树
int complete_or_not(struct Node* T){
    if(!T) return 0;
    struct Node a[100];
    int rear=0,front=-1;
    a[rear] = *T;
    if(T->lchild==NULL&&T->rchild==NULL)return 1;//如果只有一跟根节点则返回1
    if(T->lchild==NULL||T->rchild==NULL)return 0;//如果根节点有一个子树为空则返回0
    while(front!=rear){
        front++;
        //该节点的左右孩子都不为空则都入队
        if(a[front].lchild!=NULL&&a[front].rchild!=NULL){
            rear++;
            a[rear] = *a[front].lchild;
            rear++;
            a[rear] = *a[front].rchild;
        }else if(a[front].lchild==NULL&&a[front].rchild!=NULL){ //该节点的左孩子为空右孩子不为空则非完全二叉树
            return 0;
        }else if((a[front].lchild!=NULL&&a[front].rchild==NULL)||(a[front].lchild==NULL&&a[front].rchild==NULL)){ //该节点的左孩子不为空右孩子为空,或左右都为空的话,后面访问的节点必需都是叶子节点
            for(int i=front+1;i<=rear;i++){
                if(a[i].lchild!=NULL||a[i].rchild!=NULL){
                    return 0;
                }
            }//对这颗树的剩余节点进行遍历
        }
    }
    return 1;
}

int main(){
    struct Node* node;
    node = createBitree();
    if(complete_or_not(node)){
        printf("Exactly,a complete binary tree!!!\n");
    }else{
        printf("this is not a complete binary tree.");
    }
}

  • 14
    点赞
  • 76
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值