C语言实现完全二叉树的层序遍历
时间: 2023-12-12 12:34:46 浏览: 98
C语言编程之完全二叉树的层序遍历
以下是C语言实现完全二叉树的层序遍历的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 定义队列结构体
typedef struct Queue {
TreeNode **data;
int front, rear, size;
} Queue;
// 初始化队列
Queue *initQueue(int size) {
Queue *q = (Queue *)malloc(sizeof(Queue));
q->data = (TreeNode **)malloc(sizeof(TreeNode *) * size);
q->front = q->rear = 0;
q->size = size;
return q;
}
// 判断队列是否为空
int isEmpty(Queue *q) {
return q->front == q->rear;
}
// 入队
void enQueue(Queue *q, TreeNode *node) {
if (q == NULL || node == NULL) {
return;
}
q->data[q->rear++] = node;
}
// 出队
TreeNode *deQueue(Queue *q) {
if (q == NULL || isEmpty(q)) {
return NULL;
}
return q->data[q->front++];
}
// 层序遍历
void levelOrder(TreeNode *root) {
if (root == NULL) {
return;
}
Queue *q = initQueue(100);
enQueue(q, root);
while (!isEmpty(q)) {
TreeNode *node = deQueue(q);
printf("%d ", node->val);
if (node->left != NULL) {
enQueue(q, node->left);
}
if (node->right != NULL) {
enQueue(q, node->right);
}
}
}
// 创建二叉树
TreeNode *createTree(int *a, int i, int n) {
if (i >= n || a[i] == 0) {
return NULL;
}
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->val = a[i];
root->left = createTree(a, 2 * i + 1, n);
root->right = createTree(a, 2 * i + 2, n);
return root;
}
int main() {
int a[] = {1, 2, 3, 4, 5, 6, 7};
int n = sizeof(a) / sizeof(int);
TreeNode *root = createTree(a, 0, n);
levelOrder(root); // 输出:1 2 3 4 5 6 7
return 0;
}
```
阅读全文