二叉树的层序遍历及完全二叉树的判断

文章目录

1.二叉树层序遍历

2.完全二叉树的判断

文章内容

1.二叉树层序遍历

        二叉树的层序遍历需要一个队列来帮助实现。

        我们在队列中存储的是节点的地址,所以我们要对队列结构体的数据域重定义,

        

 

        以上代码 从逻辑上来讲就是1入队,1出队,2(1的左孩子)入队,4(1的右孩子)入队,2出队......

//层序遍历
void LevelOrder(BTNode* root)
{
	Que q;
	QueueInit(&q);

	if (root)
	{
		QueuePush(&q,root);
	}

	while (!QueueEmpty(&q))
	{
		BTNode* front = QueueFront(&q);
		printf("%d ",front->data);
		QueuePop(&q);

		if (front->left)
		{
			QueuePush(&q, front->left);
		}
		if (front->right)
		{
			QueuePush(&q, front->right);
		}
	}
	printf("\n");

	QueueDestroy(&q);
}

2.完全二叉树的判断

        完全二叉树的判断和二叉树的层序的思想差不多,都需要借助队列来实现。

 

 

bool TreeComplete(BTNode* root)
{
	Que q;
	QueueInit(&q);

	if (root)
	{
		QueuePush(&q, root);
	}

	while (!QueueEmpty(&q))
	{

		BTNode* front = QueueFront(&q);
	//	printf("%d ", front->data);
		QueuePop(&q);

		if (front) //front的左子树 右子树 不管为不为空都入队
		{
			QueuePush(&q, front->left);
			QueuePush(&q, front->right);
		}
		else
		{
			break;//当front 为空的时候,跳出循环开始判断是否为完全二叉树
		}
	}

	while (!QueueEmpty(root))
	{
		BTNode* front = QueueFront(&q);
		QueuePop(&q);

		if (front)
		{
			QueueDestroy(root);
			return false;
		}
	}
//	printf("\n");

	return true;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值