二叉树的层次遍历,用c语言实现
时间: 2024-08-13 15:05:25 浏览: 51
二叉树的层次遍历是一种广度优先搜索算法,它按照从上到下、从左到右的顺序遍历二叉树的所有节点。下面是用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;
int rear;
int size;
} Queue;
// 初始化队列
Queue *initQueue(int size) {
Queue *q = (Queue *)malloc(sizeof(Queue));
q->data = (TreeNode **)malloc(sizeof(TreeNode *) * size);
q->front = 0;
q->rear = 0;
q->size = size;
return q;
}
// 判断队列是否为空
int isEmpty(Queue *q) {
return q->front == q->rear;
}
// 入队
void enqueue(Queue *q, TreeNode *node) {
if (q->rear == q->size) {
printf("Queue is full.\n");
return;
}
q->data[q->rear++] = node;
}
// 出队
TreeNode *dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return NULL;
}
return q->data[q->front++];
}
// 层次遍历
void levelOrder(TreeNode *root) {
if (root == NULL) {
return;
}
Queue *q = initQueue(100);
enqueue(q, root);
while (!isEmpty(q)) {
TreeNode *node = dequeue(q);
printf("%d ", node->val);
if (node->left != NULL) {
enqueue(q, node->left);
}
if (node->right != NULL) {
enqueue(q, node->right);
}
}
}
// 创建二叉树
TreeNode *createTree() {
int val;
scanf("%d", &val);
if (val == -1) {
return NULL;
}
TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode));
node->val = val;
node->left = createTree();
node->right = createTree();
return node;
}
int main() {
TreeNode *root = createTree();
printf("Level order traversal: ");
levelOrder(root);
printf("\n");
return 0;
}
```
阅读全文