请用c语言实现二叉树的层序遍历完整代码
时间: 2023-12-18 09:52:23 浏览: 81
c语言实现二叉树的遍历
5星 · 资源好评率100%
首先,我们需要定义二叉树的结构体:
```c
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
```
然后,我们定义一个队列,用于层序遍历时保存每一层的节点:
```c
typedef struct QueueNode {
TreeNode *data;
struct QueueNode *next;
} QueueNode;
typedef struct Queue {
QueueNode *front;
QueueNode *rear;
int size;
} Queue;
```
接下来是二叉树的层序遍历函数:
```c
void levelOrder(TreeNode *root) {
if (!root) return;
Queue *q = (Queue *)malloc(sizeof(Queue));
q->front = q->rear = NULL;
q->size = 0;
// 先将根节点入队
QueueNode *node = (QueueNode *)malloc(sizeof(QueueNode));
node->data = root;
node->next = NULL;
q->front = q->rear = node;
q->size++;
while (q->size > 0) {
int level_size = q->size;
for (int i = 0; i < level_size; i++) {
// 出队并打印
TreeNode *cur = q->front->data;
printf("%d ", cur->val);
q->front = q->front->next;
q->size--;
// 左右子节点入队
if (cur->left) {
QueueNode *new_node = (QueueNode *)malloc(sizeof(QueueNode));
new_node->data = cur->left;
new_node->next = NULL;
q->rear->next = new_node;
q->rear = new_node;
q->size++;
}
if (cur->right) {
QueueNode *new_node = (QueueNode *)malloc(sizeof(QueueNode));
new_node->data = cur->right;
new_node->next = NULL;
q->rear->next = new_node;
q->rear = new_node;
q->size++;
}
}
printf("\n");
}
}
```
完整代码如下:
阅读全文