C语言写一个二叉树的层序遍历
时间: 2023-06-18 14:08:10 浏览: 96
算法之二叉树的层序遍历(利用队列实现,需熟练手写)
5星 · 资源好评率100%
下面是C语言实现二叉树的层序遍历的代码:
```c
#include <stdio.h>
#include <stdlib.h>
//定义二叉树节点结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
//定义队列节点结构体
typedef struct QueueNode {
TreeNode *node;
struct QueueNode *next;
} QueueNode;
//定义队列结构体
typedef struct Queue {
QueueNode *front;
QueueNode *rear;
} Queue;
//初始化队列
void initQueue(Queue *queue) {
queue->front = NULL;
queue->rear = NULL;
}
//判断队列是否为空
int isEmpty(Queue *queue) {
return queue->front == NULL;
}
//入队
void enqueue(Queue *queue, TreeNode *node) {
QueueNode *newNode = (QueueNode*)malloc(sizeof(QueueNode));
newNode->node = node;
newNode->next = NULL;
if (isEmpty(queue)) {
queue->front = newNode;
queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode;
}
}
//出队
TreeNode* dequeue(Queue *queue) {
if (isEmpty(queue)) {
printf("队列为空\n");
return NULL;
} else {
QueueNode *node = queue->front;
TreeNode *treeNode = node->node;
queue->front = queue->front->next;
if (queue->front == NULL) {
queue->rear = NULL;
}
free(node);
return treeNode;
}
}
//层序遍历
void levelOrder(TreeNode *root) {
Queue *queue = (Queue*)malloc(sizeof(Queue));
initQueue(queue);
enqueue(queue, root);
while (!isEmpty(queue)) {
TreeNode *node = dequeue(queue);
printf("%d ", node->val);
if (node->left) {
enqueue(queue, node->left);
}
if (node->right) {
enqueue(queue, node->right);
}
}
}
int main() {
//构建二叉树
TreeNode *node1 = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode *node2 = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode *node3 = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode *node4 = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode *node5 = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode *node6 = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode *node7 = (TreeNode*)malloc(sizeof(TreeNode));
node1->val = 1;
node2->val = 2;
node3->val = 3;
node4->val = 4;
node5->val = 5;
node6->val = 6;
node7->val = 7;
node1->left = node2;
node1->right = node3;
node2->left = node4;
node2->right = node5;
node3->left = node6;
node3->right = node7;
node4->left = NULL;
node4->right = NULL;
node5->left = NULL;
node5->right = NULL;
node6->left = NULL;
node6->right = NULL;
node7->left = NULL;
node7->right = NULL;
//层序遍历
levelOrder(node1);
return 0;
}
```
这里使用队列来实现层序遍历。首先将根节点入队,然后循环遍历队列,每次出队一个节点并打印它的值,如果它有左子树,则将左子树入队,如果它有右子树,则将右子树入队。这样可以保证每一层的节点按照从左到右的顺序被访问到。
阅读全文