C语言队列实现二叉树层次遍历
时间: 2023-05-30 11:02:08 浏览: 158
```
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100 // 队列的最大容量
// 定义二叉树结点的结构体
typedef struct TreeNode {
int data; // 数据域
struct TreeNode *left; // 左子树指针
struct TreeNode *right; // 右子树指针
} TreeNode;
// 定义队列结构体
typedef struct Queue {
TreeNode *data[MAXSIZE]; // 存放队列元素的数组
int front; // 队首指针
int rear; // 队尾指针
} Queue;
// 初始化队列
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
// 判断队列是否为空
int isEmpty(Queue *q) {
return q->front == q->rear;
}
// 判断队列是否已满
int isFull(Queue *q) {
return (q->rear + 1) % MAXSIZE == q->front;
}
// 入队操作
void enqueue(Queue *q, TreeNode *node) {
if (isFull(q)) {
printf("队列已满,无法入队!\n");
return;
}
q->data[q->rear] = node;
q->rear = (q->rear + 1) % MAXSIZE;
}
// 出队操作
TreeNode *dequeue(Queue *q) {
if (isEmpty(q)) {
printf("队列已空,无法出队!\n");
return NULL;
}
TreeNode *node = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE;
return node;
}
// 创建二叉树
TreeNode *createTree() {
int data;
scanf("%d", &data);
if (data == -1) {
return NULL;
}
TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode));
node->data = data;
node->left = createTree();
node->right = createTree();
return node;
}
// 层次遍历二叉树
void levelOrder(TreeNode *root) {
if (root == NULL) {
printf("二叉树为空!\n");
return;
}
Queue q;
initQueue(&q);
enqueue(&q, root); // 根结点入队
while (!isEmpty(&q)) {
TreeNode *node = dequeue(&q); // 出队一个结点
printf("%d ", node->data); // 访问该结点
if (node->left) {
enqueue(&q, node->left); // 左子树结点入队
}
if (node->right) {
enqueue(&q, node->right); // 右子树结点入队
}
}
printf("\n");
}
int main() {
printf("请输入二叉树的结点数据,-1表示空结点:\n");
TreeNode *root = createTree();
printf("层次遍历二叉树的结果为:\n");
levelOrder(root);
return 0;
}
```
阅读全文
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)