#include
#include
#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;
}
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);
}
}
void levelorder(binarytree*bt){
if(bt){
node*p;
p=bt->root;
queue*q;
q=create(q);
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;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)