用c语言写一个二叉树的层序遍历
时间: 2023-05-10 16:55:51 浏览: 116
算法之二叉树的层序遍历(利用队列实现,需熟练手写)
5星 · 资源好评率100%
当然可以,以下是代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 队列结构体
typedef struct Queue {
TreeNode **data;
int front, rear, size;
} Queue;
// 创建队列
Queue *createQueue(int size) {
Queue *q = (Queue *)malloc(sizeof(Queue));
q->data = (TreeNode **)malloc(sizeof(TreeNode *) * size);
q->front = q->rear = 0;
q->size = size;
return q;
}
// 入队
void enqueue(Queue *q, TreeNode *node) {
if ((q->rear + 1) % q->size == q->front) return;
q->data[q->rear] = node;
q->rear = (q->rear + 1) % q->size;
}
// 出队
TreeNode *dequeue(Queue *q) {
if (q->front == q->rear) return NULL;
TreeNode *node = q->data[q->front];
q->front = (q->front + 1) % q->size;
return node;
}
// 层序遍历
void levelOrder(TreeNode *root) {
if (!root) return;
Queue *q = createQueue(100);
enqueue(q, root);
while (q->front != q->rear) {
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->left->left = NULL;
root->left->right = NULL;
root->right = (TreeNode *)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode *)malloc(sizeof(TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode *)malloc(sizeof(TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
// 层序遍历
levelOrder(root);
return 0;
}
```
输出结果为:
```
1
2 3
4 5
```
这是二叉树的层序遍历结果。
阅读全文