用C语言写一个函数,层序遍历二叉树
时间: 2023-12-29 17:24:26 浏览: 70
举例讲解C语言程序中对二叉树数据结构的各种遍历方式
好的,下面是用C语言实现二叉树层序遍历的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct QueueNode {
struct TreeNode *data;
struct QueueNode *next;
};
struct Queue {
struct QueueNode *front;
struct QueueNode *rear;
};
void initQueue(struct Queue *q) {
q->front = NULL;
q->rear = NULL;
}
int isEmpty(struct Queue *q) {
return q->front == NULL;
}
void enqueue(struct Queue *q, struct TreeNode *node) {
struct QueueNode *newNode = (struct QueueNode *)malloc(sizeof(struct QueueNode));
newNode->data = node;
newNode->next = NULL;
if (isEmpty(q)) {
q->front = newNode;
q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
}
struct TreeNode *dequeue(struct Queue *q) {
if (isEmpty(q)) {
return NULL;
}
struct QueueNode *temp = q->front;
struct TreeNode *result = temp->data;
q->front = q->front->next;
if (q->front == NULL) {
q->rear = NULL;
}
free(temp);
return result;
}
void levelOrder(struct TreeNode *root) {
if (root == NULL) return;
struct Queue q;
initQueue(&q);
enqueue(&q, root);
while (!isEmpty(&q)) {
struct TreeNode *node = dequeue(&q);
printf("%d ", node->val);
if (node->left) enqueue(&q, node->left);
if (node->right) enqueue(&q, node->right);
}
}
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;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right->left = NULL;
root->right->right->right = NULL;
// 层序遍历
printf("层序遍历结果:");
levelOrder(root);
printf("\n");
return 0;
}
```
这里使用一个队列来辅助进行层序遍历,首先将根节点入队,然后依次出队并打印节点值,再将该节点的左右子节点入队,直到队列为空。
阅读全文