使用c语言实现层序输出二叉树
时间: 2024-02-21 12:35:14 浏览: 71
下面是使用C语言实现层序遍历二叉树的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结构体
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// 队列结构体
struct Queue {
struct TreeNode **nodes;
int head;
int tail;
int size;
};
// 创建队列
struct Queue* createQueue(int size)
{
struct Queue *queue = (struct Queue*) malloc(sizeof(struct Queue));
queue->nodes = (struct TreeNode**) malloc(size * sizeof(struct TreeNode*));
queue->head = 0;
queue->tail = 0;
queue->size = size;
return queue;
}
// 入队
void enqueue(struct Queue *queue, struct TreeNode *node)
{
queue->nodes[queue->tail++] = node;
}
// 出队
struct TreeNode* dequeue(struct Queue *queue)
{
return queue->nodes[queue->head++];
}
// 判断队列是否为空
int isEmpty(struct Queue *queue)
{
return queue->head == queue->tail;
}
// 层序遍历二叉树
void levelOrder(struct TreeNode* root) {
if (!root) {
return;
}
struct Queue *queue = createQueue(100);
enqueue(queue, root);
while (!isEmpty(queue)) {
int size = queue->tail - queue->head;
for (int i = 0; i < size; i++) {
struct TreeNode *node = dequeue(queue);
printf("%d ", node->val);
if (node->left) {
enqueue(queue, node->left);
}
if (node->right) {
enqueue(queue, node->right);
}
}
printf("\n");
}
}
// 测试代码
int main() {
struct TreeNode *root = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->right = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->left->left = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->left->left->val = 4;
root->left->right = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->left->right->val = 5;
root->right->left = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->right->left->val = 6;
root->right->right = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->right->right->val = 7;
levelOrder(root);
return 0;
}
```
输出结果为:
```
1
2 3
4 5 6 7
```
可以看到,该代码实现了层序遍历二叉树,并按层输出二叉树结点的值。
阅读全文