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

个人主页: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;

}

图解:


相关推荐
Logic1013 小时前
C语言/数据结构排序题解:三个数的最大乘积——排序后比较两种候选情况
c语言·数据结构·数组·排序·时间复杂度·算法题·负数处理
殷色玫瑰4 小时前
C++ string类详解:常用接口、字符串操作与模拟实现
java·linux·c语言·开发语言·数据结构·c++
写后端的胖头鱼6 小时前
时间复杂度 & 空间复杂度
java·数据结构·算法·时间复杂度·空间复杂度
多弗朗皮卡丘6 小时前
数据结构番外:环形队列
数据结构·c
50万马克的面包7 小时前
顺序表和链表_精华知识点_CSDN博客
数据结构·链表
All for pursuit.7 小时前
【回溯-7】494.目标和
数据结构·c++·算法·leetcode
50万马克的面包7 小时前
数据结构01-数据结构概念与复杂度-博客稿
数据结构
Logic1017 小时前
C语言/数据结构贪心算法题解:字符串趋同——逐位统计最高频率求最小修改代价
c语言·数据结构·贪心算法·字符串·时间复杂度·频率统计·算法题
红豆诗人9 小时前
C++二叉搜索树:查找、插入和删除为什么这样写
数据结构·c++·算法
H.莓飛9 小时前
【数据结构】堆_OJ题
linux·数据结构·算法