#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct tree
{
int data;
struct tree* lchild;
struct tree* rchild;
};
struct LinkNode {
struct tree **data;//
struct LinkNode* next;
};
struct LinkQueue {
struct LinkNode* front, * rear; //队列的队头和队尾指针
};
void InitQueue(struct LinkQueue* Q)
{
Q->front = Q->rear = (struct LinkNode *)malloc(sizeof(struct LinkNode)); //建立头结点
Q->front->next = NULL; //初始为空
}
void enqueue(struct LinkQueue* Q, struct tree * e)
{
struct LinkNode * s = (struct LinkNode *)malloc(sizeof(struct LinkNode));
s->data = &e;
s->next = NULL;
Q->rear->next = s; //把拥有元素e新结点s赋值给原队尾结点的后继 //把当前的s设置为新的队尾结点
Q->rear = s;
}
struct tree * dequeue(struct LinkQueue* Q) {
struct LinkNode *p;
struct tree* e = NULL;
p = Q->front->next;
e =*( p->data);
Q->front->next = p->next;
free(p);
return e;
}
void create(struct tree **t)
{
int data;
scanf_s("%d", &data);
if (data == -1)
{
* t= NULL;
return;
}
else
{
*t = (struct tree*)malloc(sizeof(struct tree));
if (!(*t))
{
printf("error");
exit(-1);
}
}
(*t)->data = data;
printf("请输入%d左子树:", data);
create(&(*t)->lchild);
printf("请输入%d右子树:", data);
create(&(*t)->rchild);
}
void showbfs(struct tree* s,struct LinkQueue *t)
{
enqueue(t, s);
struct tree* e = NULL;
while(1)
{
e=dequeue(t);
printf("%d ", e->data);
if (e->lchild != NULL)
{
enqueue(t, e->lchild);
}
if (e->rchild!=NULL)
enqueue(t, e->rchild);
}
}
int main()
{
struct tree* s;
struct LinkQueue* t= (struct LinkQueue*)malloc(sizeof(struct LinkQueue));
InitQueue(t);
create(&s);
showbfs(s, t);
}
/*1)树结点类型定义为:
2)编写一般树的创建函数,输入下面树,保存到二叉树的结构里。
输入: 5 3 2 6 0 3 9 0 2 4 3 0
3)基于二叉树编写树的广度遍历函数,输出遍历结果
(5,3,2,。。。。);
4)编写main()函数,先调用create函数,建立一棵树;然后输出广度遍历序列到屏幕上。
*/