栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

#include 
#include 

//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.");
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/529023.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号