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

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

}

图解:


相关推荐
东华万里13 分钟前
第31篇 数据结构入门:顺序表
数据结构·大学生专区
Vect__1 小时前
Go 数据结构 slice 深度剖析
开发语言·数据结构·golang
青山木1 小时前
Hot 100 --- LRU 缓存
java·数据结构·算法·leetcode·链表·缓存·哈希
剑挑星河月3 小时前
35.搜索插入位置
java·数据结构·算法·leetcode
闪电悠米3 小时前
力扣hot100-438.找到字符串中所有字母异位词-固定长度滑动窗口详解
linux·服务器·数据结构·算法·leetcode·滑动窗口·力扣hot100
人道领域3 小时前
【LeetCode刷题日记】51.N皇后
数据结构·算法
金融小师妹17 小时前
人工智能推演框架:非农降温信号如何重构黄金定价模型
数据结构·人工智能·机器学习·transformer
ysa05103020 小时前
【并查集】判环,深搜
数据结构·c++·算法·深度优先
YuK.W21 小时前
Leetcode100: 94.二叉树中序遍历、104.二叉树最大深度、226.翻转二叉树
java·算法·leetcode·二叉树
.Hypocritical.21 小时前
数据结构笔记——链表成环/反转 + 有序二叉树(BST)构建、遍历、删除
java·数据结构