c语言二叉树层序遍历
时间: 2023-12-07 19:39:48 浏览: 108
二叉树的层序遍历是一种广度优先搜索算法,它按照层的顺序遍历二叉树的节点。下面是C语言实现二叉树层序遍历的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树的结构体
typedef struct BTnode {
char element;
struct BTnode *left;
struct BTnode *right;
} *BTnodePtr;
// 队列的结构体
typedef struct Queue {
BTnodePtr *data;
int front, rear;
int maxSize;
} *QueuePtr;
// 初始化队列
QueuePtr initQueue(int maxSize) {
QueuePtr q = (QueuePtr)malloc(sizeof(struct Queue));
q->data = (BTnodePtr*)malloc(sizeof(BTnodePtr) * maxSize);
q->front = q->rear = 0;
q->maxSize = maxSize;
return q;
}
// 判断队列是否为空
int isEmpty(QueuePtr q) {
return q->front == q->rear;
}
// 添加元素
void enqueue(QueuePtr q, BTnodePtr x) {
if ((q->rear + 1) % q->maxSize == q->front) {
printf("Queue is full.\n");
return;
}
q->data[q->rear] = x;
q->rear = (q->rear + 1) % q->maxSize;
}
// 删除元素
BTnodePtr dequeue(QueuePtr q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return NULL;
}
BTnodePtr x = q->data[q->front];
q->front = (q->front + 1) % q->maxSize;
return x;
}
// 创建结点
BTnodePtr createNode(char element) {
BTnodePtr node = (BTnodePtr)malloc(sizeof(struct BTnode));
node->element = element;
node->left = node->right = NULL;
return node;
}
// 创建二叉树
BTnodePtr createTree() {
BTnodePtr root = createNode('A');
root->left = createNode('B');
root->right = createNode('C');
root->left->left = createNode('D');
root->left->right = createNode('E');
root->right->left = createNode('F');
root->right->right = createNode('G');
return root;
}
// 层次遍历
void levelOrder(BTnodePtr root) {
QueuePtr q = initQueue(100);
enqueue(q, root);
while (!isEmpty(q)) {
BTnodePtr node = dequeue(q);
printf("%c ", node->element);
if (node->left != NULL) {
enqueue(q, node->left);
}
if (node->right != NULL) {
enqueue(q, node->right);
}
}
}
// 主函数
int main() {
BTnodePtr root = createTree();
printf("Level order traversal of binary tree is: ");
levelOrder(root);
printf("\n");
return 0;
}
```
阅读全文