#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef char datatype;
typedef struct node {
datatype data;
struct node* lchild;
struct node* rchild;
}node;
typedef struct binarytree {
node* root;
}binarytree;
binarytree* nulltree(binarytree* bt) {
bt->root = NULL;
return bt;
}
binarytree* makebtree(binarytree* bt, datatype x, binarytree* ltree, binarytree* rtree) {
bt->root = (node*)malloc(sizeof(node));
bt->root->data = x;
bt->root->lchild = ltree->root;
bt->root->rchild = rtree->root;
return bt;
}
void preorder(node* root) {
if (root) {
printf("%c", root->data);
preorder(root->lchild);
preorder(root->rchild);
}
}
void preoredertree(binarytree* bt) {
if (bt->root) {
preorder(bt->root);
printf("\n");
}
}
typedef struct qnode {
int front;
int rear;
node* data[MAXSIZE];
}queue;
queue* create() {
queue* q;
q = (qnode*)malloc(sizeof(qnode));
q->front = q->rear = 0;
return q;
}
queue* inselem(queue* q, node* btnode) {
if (q && btnode) {
if ((q->rear + 1) % MAXSIZE != q->front) {
int ret = (q->rear + 1) % MAXSIZE;
q->data[ret] = btnode;
q->rear = (q->rear + 1) % MAXSIZE;
return q;
}
else
printf("this queue is full\n");
}
}
queue* deldata(queue* q) {
if (q) {
if (q->front != q->rear) {
int ret = (q->front + 1) % MAXSIZE;
q->data[ret] = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE;
return q;
}
else
printf("this queue is empty");
}
else
printf("this queue is not exist\n");
}
bool isempty(queue* q) {
return q->front == q->rear;
}
node* front(queue* q) {
node* p;
p = q->data[(q->front + 1) % MAXSIZE];
return p;
}
queue* destroy(queue* q) {
if (q) {
while (!isempty(q)) {
deldata(q);
}
free(q);
}
return q;
}
void levelorder(binarytree* bt) {
if (bt) {
node* p;
p = bt->root;
queue* q;
q = create();
inselem(q, p);
while (!isempty(q)) {
printf("%c", p->data);
deldata(q);
if (p->lchild)
inselem(q, p->lchild);
if (p->rchild)
inselem(q, p->rchild);
p = front(q);
}
destroy(q);
printf("\n");
}
}
int main() {
binarytree bt1, bt2, bt3, bt4, bt5;
nulltree(&bt5);
makebtree(&bt2, 'B', &bt5, &bt5);
makebtree(&bt4, 'D', &bt5, &bt5);
makebtree(&bt3, 'C', &bt4, &bt5);
makebtree(&bt1, 'A', &bt2, &bt3);
preoredertree(&bt1);
levelorder(&bt1);
levelorder(&bt3);
return 0;
}
运行结果