C语言【问题描述】 按层序遍历打印二叉树。(队列操作采用循环队列) 【输入形式】 二叉树的先序扩展序列(字符串,以#填充空白结点) 【输出形式】 层序遍历打印二叉树 【样例输入】 image.png ABC##DE#G##F### 【样例输出】 ABCDEFG
时间: 2023-08-05 11:01:59 浏览: 91
C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
以下是C语言的代码实现,使用循环队列来实现二叉树的层序遍历:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct TreeNode {
char data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode, *Tree;
typedef struct Queue {
TreeNode *data[MAXSIZE];
int front, rear;
} Queue;
// 初始化队列
void initQueue(Queue *q) {
q->front = 0;
q->rear = 0;
}
// 判断队列是否为空
int isEmpty(Queue *q) {
return q->front == q->rear;
}
// 入队
void enqueue(Queue *q, TreeNode *node) {
if ((q->rear + 1) % MAXSIZE == q->front) {
printf("Queue is full.\n");
return;
}
q->data[q->rear] = node;
q->rear = (q->rear + 1) % MAXSIZE;
}
// 出队
TreeNode *dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return NULL;
}
TreeNode *node = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE;
return node;
}
// 创建二叉树
Tree createTree() {
char c;
scanf("%c", &c);
if (c == '#') {
return NULL;
}
Tree tree = (Tree)malloc(sizeof(TreeNode));
tree->data = c;
tree->left = createTree();
tree->right = createTree();
return tree;
}
// 层序遍历
void levelTraversal(Tree tree) {
if (tree == NULL) {
return;
}
Queue q;
initQueue(&q);
enqueue(&q, tree);
while (!isEmpty(&q)) {
TreeNode *node = dequeue(&q);
printf("%c", node->data);
if (node->left != NULL) {
enqueue(&q, node->left);
}
if (node->right != NULL) {
enqueue(&q, node->right);
}
}
}
int main() {
Tree tree = NULL;
printf("Please input the preorder sequence of the binary tree: ");
tree = createTree();
printf("The level order traversal of the binary tree is: ");
levelTraversal(tree);
printf("\n");
return 0;
}
```
输入样例:
```
ABC##DE#G##F###
```
输出样例:
```
The level order traversal of the binary tree is: ABCDEFG
```
阅读全文