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

个人主页:Lei宝啊

愿所有美好如期而遇


目录

二叉树层序遍历:

判断完全二叉树:


二叉树层序遍历:

层序遍历就是一层一层,从上到下遍历,上图遍历结果为:4 2 7 1 3 6 9


思路:

通过队列来实现层序遍历,让父节点带孩子节点。将父节点入队列,当其孩子节点不为空时,入队列,将父节点出队列,依次类推。

代码:

树的结构:

复制代码
typedef struct BT_Tree
{
	char data;
	struct BT_Tree* left;
	struct BT_Tree* right;
}BT_Tree;

队列结构:

复制代码
typedef struct BT_Tree* DataType;
typedef struct Queue
{
	DataType data;
	struct Queue *next;
}Queue;

typedef struct Q
{
	Queue* head;
	Queue* tail;
	int size;
}Q;

层序实现:

复制代码
void Sequence(BT_Tree* node)
{
	if (node == NULL)
	{
		printf("NULL\n");
		return;
	}

	Q queue;
	Init(&queue);

	QueuePush(&queue, node);
	while (!Empty(&queue))
	{
		BT_Tree* front = GetQueueFrontNum(&queue);
		printf("%d ", front->data);

		if (front->left)
			QueuePush(&queue, front->left);

		if (front->right)
			QueuePush(&queue, front->right);

		QueuePop(&queue);
	}

}

图解:


判断完全二叉树:

思路:

这里同层序遍历的思路非常相似,但是不同的地方在于这里孩子节点为空我们仍要将其入队列,最后我们检查队列,若队列空后仍有非空的值,则不是完全二叉树。

代码:

复制代码
bool JudgeTreeComplete(BT_Tree* node)
{
	if (node == NULL)
		return true;

	Q queue;
	Init(&queue);

	QueuePush(&queue, node);
	while (!Empty(&queue))
	{
		BT_Tree* front = GetQueueFrontNum(&queue);
		if (front == NULL)
			break;
	
		QueuePush(&queue, front->left);
		QueuePush(&queue, front->right);

		QueuePop(&queue);
	}

	while (!Empty(&queue))
	{
		BT_Tree* front = GetQueueFrontNum(&queue);
		if (front != NULL)
		{
			Destroy(&queue);
			return false;
		}
		QueuePop(&queue);
	}

	Destroy(&queue);
	return true;

}

图解:


相关推荐
云手机掌柜2 小时前
从0到500账号管理:亚矩阵云手机多开组队与虚拟定位实战指南
数据结构·线性代数·网络安全·容器·智能手机·矩阵·云计算
没书读了5 小时前
考研复习-数据结构-第八章-排序
数据结构
waveee1236 小时前
学习嵌入式的第三十四天-数据结构-(2025.7.29)数据库
数据结构·数据库·学习
jie*7 小时前
小杰数据结构(one day)——心若安,便是晴天;心若乱,便是阴天。
数据结构
伍哥的传说8 小时前
React & Immer 不可变数据结构的处理
前端·数据结构·react.js·proxy·immutable·immer·redux reducers
ZTLJQ10 小时前
专业Python爬虫实战教程:逆向加密接口与验证码突破完整案例
开发语言·数据结构·爬虫·python·算法
努力的小帅11 小时前
C++_红黑树树
开发语言·数据结构·c++·学习·算法·红黑树
逐花归海.11 小时前
『 C++ 入门到放弃 』- 哈希表
数据结构·c++·程序人生·哈希算法·散列表
qqxhb13 小时前
零基础数据结构与算法——第六章:算法设计范式与高级主题-设计技巧(上)
java·数据结构·算法·分解·空间换时间·时空平衡
xiaofann_13 小时前
【数据结构】用堆实现排序
数据结构