帮我用C语言写一个二叉树层序遍历问题
时间: 2023-06-11 09:08:31 浏览: 109
好的,下面是用C语言实现二叉树层序遍历的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树节点结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 定义队列结构体
typedef struct Queue {
struct TreeNode* data[100];
int front;
int rear;
} Queue;
// 初始化队列
Queue* initQueue() {
Queue* q = (Queue*)malloc(sizeof(Queue));
q->front = 0;
q->rear = 0;
return q;
}
// 入队
void enqueue(Queue* q, TreeNode* node) {
q->data[q->rear++] = node;
}
// 出队
TreeNode* dequeue(Queue* q) {
return q->data[q->front++];
}
// 判断队列是否为空
int isEmpty(Queue* q) {
return q->front == q->rear;
}
// 二叉树层序遍历
void levelOrder(TreeNode* root) {
if (root == NULL) {
return;
}
Queue* q = initQueue();
enqueue(q, root);
while (!isEmpty(q)) {
int size = q->rear - q->front;
for (int i = 0; i < size; i++) {
TreeNode* node = dequeue(q);
printf("%d ", node->val);
if (node->left) {
enqueue(q, node->left);
}
if (node->right) {
enqueue(q, node->right);
}
}
printf("\n");
}
}
int main() {
// 构建二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 6;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 7;
// 二叉树层序遍历
levelOrder(root);
return 0;
}
```
运行结果如下:
```
1
2 3
4 5 6 7
```
阅读全文