判断一棵二叉树是否是完全二叉树

题目:判断一棵二叉树是否是完全二叉树
思路:
1.首先明确完全二叉树的概念。完全二叉树除最后一层外,所有层结点数均达到最大值,最后一层结点连续集中在最左边。空树也是完全二叉树。
2.我们可以通过层序遍历的方式遍历这个二叉树,使用一个队列存储遍历的结点。可以利用最后一层的结点集中在左侧这个特性解题,具体看代码:


代码:

bool isCompleteTree(pTree pT)
{
	Queue q;
	initQueue(&q);
	Enqueue(&q,pT);//根入队
	pNode ptr = NULL;
	while((ptr = Dequeue(&q)) != NULL)//不断出队,直到遇到空
	{
		Enqueue(&q,ptr->left);//入队左孩子,空结点也同样入队
		Enqueue(&q,ptr->right);//入队右孩子
	}
	while(!isQueueEmpty(&q))//如果队列非空,那么留在队列中的必然都是NULL结点
	{
		ptr = Dequeue(&q);
		if(ptr != NULL)//如果存在非null结点,说明不是完全二叉树
		{
			return false;
		}
	}
	return true;
}
完整代码:
/*
判断是否是完全二叉树
by Rowandjj
2014/8/19
*/
#include<iostream>
using namespace std;
typedef struct _NODE_
{
	int data;
	struct _NODE_ *left;
	struct _NODE_ *right;
}Node,*pNode,*pTree;
typedef struct _QUEUENODE_
{
	pNode queue_data;
	struct _QUEUENODE_ *next;
}QueueNode,*pQueueNode;
typedef struct _QUEUE_
{
	pQueueNode pHead;
	pQueueNode pTail;
	int size;
}Queue,*pQueue;
void initQueue(pQueue pQ)
{
	pQ->pHead = pQ->pTail = (pQueueNode)malloc(sizeof(QueueNode));
	if(!pQ->pTail)
	{
		exit(-1);
	}
	pQ->pHead->next = NULL;
	pQ->size = 0;
}
void Enqueue(pQueue pQ,pNode data)
{
	if(pQ == NULL)
	{
		return;
	}
	pQueueNode pNew = (pQueueNode)malloc(sizeof(QueueNode));
	if(!pNew)
	{
		exit(-1);
	}
	pNew->queue_data = data;
	pNew->next = NULL;
	pQ->pTail->next = pNew;
	pQ->pTail = pNew;
	pQ->size++;
}
pNode Dequeue(pQueue pQ)
{
	if(pQ == NULL)
	{
		return NULL;
	}
	pQueueNode pDel = pQ->pHead->next;
	if(pDel == NULL)
	{
		return NULL;
	}else
	{
		pNode result = pDel->queue_data;
		if(pQ->pTail == pDel)
		{
			pQ->pTail = pQ->pHead;
		}
		pQ->pHead->next = pDel->next;
		pQ->size--;
		free(pDel);
		return result;
	}
}
bool isQueueEmpty(pQueue pQ)
{
	return pQ->size == 0;
}
bool isCompleteTree(pTree pT)
{
	Queue q;
	initQueue(&q);
	Enqueue(&q,pT);
	pNode ptr = NULL;
	while((ptr = Dequeue(&q)) != NULL)
	{
		Enqueue(&q,ptr->left);
		Enqueue(&q,ptr->right);
	}
	while(!isQueueEmpty(&q))
	{
		ptr = Dequeue(&q);
		if(ptr != NULL)
		{
			return false;
		}
	}
	return true;
}
void createTree(pTree *pRoot)
{
	int data;
	cin>>data;
	if(data == -1)
	{
		return;
	}
	*pRoot = (pNode)malloc(sizeof(Node));
	if(*pRoot == NULL)
	{
		exit(-1);
	}
	(*pRoot)->data = data;
	(*pRoot)->left = NULL;
	(*pRoot)->right = NULL;
	createTree(&(*pRoot)->left);
	createTree(&(*pRoot)->right);
}
void displayTree(pTree pT)
{
	if(pT == NULL)
	{
		return;
	}
	cout<<pT->data<<" ";
	if(pT->left)
	{
		displayTree(pT->left);
	}
	if(pT->right)
	{
		displayTree(pT->right);
	}
}
int main()
{
	pTree p = NULL;
	createTree(&p);
	cout<<isCompleteTree(p)<<endl;
	displayTree(p);
	cout<<endl;
	return 0;
}



  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值