c语言实现树的层序遍历
时间: 2023-10-15 17:02:03 浏览: 86
树的层次遍历.c
树的层序遍历可以使用队列来实现,具体步骤如下:
1. 首先将根节点入队。
2. 当队列非空时,取出队首节点,并将其值输出。
3. 将该节点的左子节点和右子节点(如果存在)入队。
4. 重复步骤2和3,直到队列为空。
以下是C语言实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 树节点结构体
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// 队列结构体及相关操作
struct QueueNode {
struct TreeNode *node;
struct QueueNode *next;
};
struct Queue {
struct QueueNode *front;
struct QueueNode *rear;
};
void enqueue(struct Queue *queue, struct TreeNode *node) {
struct QueueNode *newNode = (struct QueueNode*)malloc(sizeof(struct QueueNode));
newNode->node = node;
newNode->next = NULL;
if (queue->rear == NULL) {
queue->front = queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode;
}
}
struct TreeNode* dequeue(struct Queue *queue) {
if (queue->front == NULL) {
return NULL;
}
struct QueueNode *node = queue->front;
struct TreeNode *result = node->node;
queue->front = node->next;
if (queue->front == NULL) {
queue->rear = NULL;
}
free(node);
return result;
}
// 层序遍历函数
void levelOrder(struct TreeNode* root) {
if (root == NULL) {
return;
}
struct Queue queue = {NULL, NULL};
enqueue(&queue, root);
while (queue.front != NULL) {
struct TreeNode *node = dequeue(&queue);
printf("%d ", node->val);
if (node->left != NULL) {
enqueue(&queue, node->left);
}
if (node->right != NULL) {
enqueue(&queue, 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->left->left = NULL;
root->left->right = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
// 输出层序遍历结果
levelOrder(root);
return 0;
}
```
输出结果为:1 2 3 4 5。
阅读全文