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

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

}

图解:


相关推荐
Sylvia-girl7 小时前
数据结构之复杂度
数据结构·算法
CQ_YM8 小时前
数据结构之队列
c语言·数据结构·算法·
VekiSon8 小时前
数据结构与算法——树和哈希表
数据结构·算法
xu_yule8 小时前
数据结构与算法(1)(第一章复杂度知识点)(大O渐进表示法)
数据结构
fish_xk9 小时前
数据结构之排序
数据结构
Unstoppable229 小时前
代码随想录算法训练营第 56 天 | 拓扑排序精讲、Dijkstra(朴素版)精讲
java·数据结构·算法·
potato_may10 小时前
CC++ 内存管理 —— 程序的“五脏六腑”在哪里?
c语言·开发语言·数据结构·c++·内存·内存管理
天赐学c语言11 小时前
12.5 - 二叉树的最近公共祖先 && 构造函数和析构函数可以是虚函数吗
c++·二叉树·虚函数
ghie909011 小时前
MATLAB自适应子空间辨识工具箱
数据结构·算法·matlab
松涛和鸣12 小时前
25、数据结构:树与二叉树的概念、特性及递归实现
linux·开发语言·网络·数据结构·算法