C语言层序创建二叉树
时间: 2024-01-23 18:13:18 浏览: 84
以下是C语言层序创建二叉树的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
/* 节点结构 */
typedef struct node {
char a;
struct node* leftchild, * rightchild;
} Bitree;
/* 队列结构 */
typedef struct queue {
Bitree* data[MAX_SIZE];
int front, rear;
} Queue;
/* 初始化队列 */
void initQueue(Queue* q) {
q->front = q->rear = 0;
}
/* 判断队列是否为空 */
int isEmpty(Queue* q) {
return q->front == q->rear;
}
/* 入队 */
void enQueue(Queue* q, Bitree* node) {
if ((q->rear + 1) % MAX_SIZE == q->front) {
printf("Queue is full.\n");
return;
}
q->data[q->rear] = node;
q->rear = (q->rear + 1) % MAX_SIZE;
}
/* 出队 */
Bitree* deQueue(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return NULL;
}
Bitree* res = q->data[q->front];
q->front = (q->front + 1) % MAX_SIZE;
return res;
}
/* 层序创建二叉树 */
void create(Bitree** T) {
Queue q;
initQueue(&q);
char a;
scanf("%c", &a);
if (a == '#') {
*T = NULL;
return;
}
*T = (Bitree*)malloc(sizeof(Bitree));
(*T)->a = a;
(*T)->leftchild = (*T)->rightchild = NULL;
enQueue(&q, *T);
while (!isEmpty(&q)) {
Bitree* node = deQueue(&q);
scanf("%c", &a);
if (a == '#') {
node->leftchild = NULL;
}
else {
node->leftchild = (Bitree*)malloc(sizeof(Bitree));
node->leftchild->a = a;
node->leftchild->leftchild = node->leftchild->rightchild = NULL;
enQueue(&q, node->leftchild);
}
scanf("%c", &a);
if (a == '#') {
node->rightchild = NULL;
}
else {
node->rightchild = (Bitree*)malloc(sizeof(Bitree));
node->rightchild->a = a;
node->rightchild->leftchild = node->rightchild->rightchild = NULL;
enQueue(&q, node->rightchild);
}
}
}
/* 先序遍历 */
void preOrder(Bitree* T) {
if (T == NULL) {
return;
}
printf("%c ", T->a);
preOrder(T->leftchild);
preOrder(T->rightchild);
}
int main() {
Bitree* T;
create(&T);
printf("先序遍历结果:");
preOrder(T);
printf("\n");
return 0;
}
```
阅读全文