数据结构——完全二叉树的判断【非递归算法】(C语言)

  • 完全二叉树的判断
    下面给出两个列子(序号只是为了输入方便,并不代表完全二叉树的编号顺序)其中,列1为非完全二叉树【高度差大于2】,列2为完全二叉树。
    在这里插入图片描述
#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include <iostream>
#define MAXSIZE   10010
#define ElemType int
using namespace std;
typedef struct BTNode{
    ElemType data;
    BTNode *lchild,*rchild;
}*BTree;
//先序建树
BTree CreateTree(){
    ElemType ch;
    printf("输入结点元素值:");
    scanf("%d",&ch);
    if(ch == 0)
        return NULL;
    else{
        BTree tree=(BTree)malloc(sizeof(BTree));
        tree->data=ch;
        printf("%d 结点左子树\n",ch);
        tree->lchild=CreateTree();
        printf("%d 结点右子树\n",ch);
        tree->rchild=CreateTree();
        return tree;
    }
}
//层次遍历
void LayeredOrderTravel(BTree tree){
    queue<BTree> queue1;
    BTree p;
    if(tree){//树非空
        //入队与队列指针(下标)初始化
       queue1.push(tree);
       while(!queue1.empty()){//队列非空
            p=queue1.front();//队头元素出队并访问
            queue1.pop();
            printf("%d ",p->data);//访问
            if(p->lchild)//左孩子不为空则入队
                queue1.push(p->lchild);
            if(p->rchild)//右孩子不为空则入队
                queue1.push(p->rchild);
       }
    }
}
bool ISCompleteTree(BTree tree){
    queue<BTree> queue1;
    BTree p;
    int flag=false;
    if(tree){
        queue1.push(tree);
        while(!queue1.empty()){
            p=queue1.front();
            queue1.pop();
            if(flag){//可能出现为非完全二叉树的情况的检测
                if((p->lchild)||(p->rchild))
                    return false;
            }else{
                if((p->rchild)&&!(p->lchild))//有右无左(非完全二叉树)
                    return false;
                else if((p->lchild)&&!(p->rchild)){//有左无右
                    //有左无右的情况时(flag=true,检测是否存在孩子,若有则为非完全二叉树)
                    queue1.push(p->lchild);
                    flag=true;
                }else if((p->lchild)&&(p->rchild)){//有左有右
                    queue1.push(p->lchild);
                    queue1.push(p->rchild);
                }else{//其他情况
                    //某个结点为叶子结点,检查其兄弟结点的孩子是否还有孩子(层数相差大于2,非完全二叉树)
                    //这里为检查其兄弟结点孩子结点的孩子结点是因为其兄弟结点的孩子结点在上面的判断中
                    //已经入队列,下次执行if(flag)里面的判断时即为检查的其兄弟结点孩子结点的孩子结点
                    flag=true;
                }
            }
        }//while
    }//if
    return true;
 }
int main(){
    printf("二叉树的建立\n");
    BTree tree;
    tree=CreateTree();
    printf("二叉树的层序遍历\n");
    LayeredOrderTravel(tree);
    printf("\n判断是否为完全二叉树\n");
    bool flag=ISCompleteTree(tree);
    if(flag)
        printf("该树为完全二叉树\n");
    else
        printf("该树为非完全二叉树\n");
    return 0;
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 4
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值