c语言层次遍历二叉树完整代码
时间: 2024-05-27 11:06:53 浏览: 155
C语言层次遍历二叉树
C语言层次遍历二叉树的完整代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
// 树节点的结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 定义队列结构体
typedef struct QueueNode {
struct TreeNode* data;
struct QueueNode* next;
} QueueNode;
// 定义队列
typedef struct Queue {
QueueNode* front;
QueueNode* rear;
} Queue;
// 初始化队列
void initQueue(Queue* q) {
q->front = q->rear = NULL;
}
// 判断队列是否为空
int isEmpty(Queue* q) {
return q->front == NULL;
}
// 入队
void enqueue(Queue* q, TreeNode* node) {
QueueNode* newNode = (QueueNode*)malloc(sizeof(QueueNode));
newNode->data = node;
newNode->next = NULL;
if (isEmpty(q)) {
q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
}
// 出队
TreeNode* dequeue(Queue* q) {
if (isEmpty(q)) {
return NULL;
}
QueueNode* node = q->front;
TreeNode* data = node->data;
if (q->front == q->rear) {
q->front = q->rear = NULL;
} else {
q->front = q->front->next;
}
free(node);
return data;
}
// 层次遍历二叉树
void levelOrderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
Queue q;
initQueue(&q);
enqueue(&q, root);
while (!isEmpty(&q)) {
TreeNode* node = dequeue(&q);
printf("%d ", node->val);
if (node->left) {
enqueue(&q, node->left);
}
if (node->right) {
enqueue(&q, node->right);
}
}
}
int main() {
// 构造二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
TreeNode* left = (TreeNode*)malloc(sizeof(TreeNode));
left->val = 2;
TreeNode* right = (TreeNode*)malloc(sizeof(TreeNode));
right->val = 3;
TreeNode* leftLeft = (TreeNode*)malloc(sizeof(TreeNode));
leftLeft->val = 4;
TreeNode* leftRight = (TreeNode*)malloc(sizeof(TreeNode));
leftRight->val = 5;
root->left = left;
root->right = right;
left->left = leftLeft;
left->right = leftRight;
right->left = right->right = leftLeft->left = leftLeft->right = leftRight->left = leftRight->right = NULL;
// 层次遍历二叉树
levelOrderTraversal(root);
return 0;
}
```
在代码中,我们使用了队列来实现层次遍历。具体思路是先将根节点入队,然后依次出队,访问其左右子节点,再将左右子节点入队,以此类推,直到队列为空。
阅读全文