完全二叉树的层序遍历C语言
时间: 2024-05-09 08:12:14 浏览: 132
完全二叉树是一种特殊的二叉树,它除了最后一层节点可能不满外,其他每一层的节点数都达到了最大值。层序遍历是指从根节点开始,按照从上到下、从左到右的顺序遍历每个节点。以下是完全二叉树层序遍历的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 QueueNode* initQueue() {
struct QueueNode *queue = (struct QueueNode*)malloc(sizeof(struct QueueNode));
queue->next = NULL;
return queue;
}
// 入队操作
void enQueue(struct QueueNode *queue, struct TreeNode *node) {
struct QueueNode *temp = (struct QueueNode*)malloc(sizeof(struct QueueNode));
temp->node = node;
temp->next = NULL;
while (queue->next != NULL) {
queue = queue->next;
}
queue->next = temp;
}
// 出队操作
struct TreeNode* deQueue(struct QueueNode *queue) {
struct QueueNode *temp = queue->next;
struct TreeNode *res = temp->node;
queue->next = temp->next;
free(temp);
return res;
}
// 层序遍历
void levelOrder(struct TreeNode* root) {
if (root == NULL) {
return;
}
struct QueueNode *queue = initQueue();
enQueue(queue, root);
while (queue->next != NULL) {
struct TreeNode *temp = deQueue(queue);
printf("%d ", temp->val);
if (temp->left != NULL) {
enQueue(queue, temp->left);
}
if (temp->right != NULL) {
enQueue(queue, temp->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;
// 调用层序遍历函数
levelOrder(root);
return 0;
}
```
阅读全文