基本思路:使用队列按层次遍历二叉树,遍历过程中将二叉树的所有结点依次入队。当出队遇见一个NULL结点时,若遍历其后结点都为NULL则为完全二叉树,否则不是完全二叉树。因为层次遍历完全二叉树时,当遍历到空结点时前面所有非空结点已经被遍历完了,若空结点之后还有非空结点则不是完全二叉树。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/*判断一个二叉树是不是完全二叉树*/
//先序创建二叉树
typedef struct TNode
{
int data;
struct TNode *left;
struct TNode *right;
} TNode,*PTNode;
PTNode createTree()
{
PTNode ptnode;
printf("输入结点值:");
int data;
scanf("%d",&data);
if(data==0)
{
ptnode = NULL;
}
else
{
ptnode = (PTNode)malloc(sizeof(TNode));
ptnode->data = data;
ptnode->left = createTree();
ptnode->right = createTree();
}
return ptnode;
}
//先序打印二叉树
void print(PTNode ptnode)
{
if(ptnode!=NULL)
{
printf("%d ",ptnode->data);
print(ptnode->left);
print(ptnode->right);
}
}
//创建队列
typedef struct QNode
{
PTNode ptnode;
struct QNode *next;
}QNode,*PQNode;
typedef struct Queue
{
PQNode front;
PQNode rear;
}Queue,*PQueue;
PQueue initQueue()
{
PQueue pqueue = (PQueue)malloc(sizeof(Queue));
PQNode pqnode = (PQNode)malloc(sizeof(QNode));
if(pqnode == NULL)
{
printf("init queue error\n");
exit(-1);
}
pqueue->front = pqnode;
pqueue->rear = pqnode;
pqueue->front->next = NULL;
return pqueue;
}
void enQueue(PQueue pqueue,PTNode ptnode)
{
PQNode pqnode = (PQNode)malloc(sizeof(QNode));
if(pqnode == NULL)
{
printf("enqueue error\n");
exit(-1);
}
pqnode->ptnode = ptnode;
pqnode->next = NULL;
pqueue->rear->next = pqnode;
pqueue->rear = pqnode;
}
PTNode deQueue(PQueue pqueue)
{
if(pqueue->front == pqueue->rear)
{
printf("deQueue error! queue is null\n");
exit(-1);
}
PQNode p = pqueue->front->next;
pqueue->front->next = p->next;
if(p == pqueue->rear)
{
pqueue->rear = pqueue->front;
}
PTNode ptnode = p->ptnode;
free(p);
return ptnode;
}
bool isEmpty(PQueue pqueue)
{
if(pqueue->front == pqueue->rear)
{
return true;
}
return false;
}
//判断二叉树是不是完全二叉树
bool isFullBintree(PTNode root)
{
PQueue pqueue = initQueue();
if(root==NULL)
return true;
PTNode cur = NULL; //指向队列头结点中的二叉树节点的指针
enQueue(pqueue,root);
while((cur = deQueue(pqueue))!=NULL) //层次遍历树结点,遇见空结点停止遍历
{
printf("%d \n",cur->data); //层次遍历输出结点值,若为完全二叉树则输出为层次遍历结果
enQueue(pqueue,cur->left);
enQueue(pqueue,cur->right);
}
while(!isEmpty(pqueue)) //检查空结点之后结点,如果有非空结点则不是完全二叉树
{
if(deQueue(pqueue)!=NULL)
return false;
}
return true;
}
int main(int argc, char *argv[]) {
PTNode root;
root = createTree();
print(root);
printf("\n");
if(isFullBintree(root))
{
printf("is full binary tree\n");
}
else
{
printf("not full binary tree\n");
}
return 0;
}
本文介绍了一种通过队列层次遍历的方法来判断一个给定的二叉树是否为完全二叉树。通过创建二叉树并进行层次遍历,如果遇到空节点后仍有非空节点,则该树不是完全二叉树。
4732

被折叠的 条评论
为什么被折叠?



