二叉树层序遍历问题。要求:1编写一个创建二叉树的函数2编写按层次(同一层自左到右)输出二叉树中所有节

2025-05-10 11:10:02
推荐回答(1个)
回答1:

这是小地刚编完的,能运行
#include"stdio.h"
#include"malloc.h"
typedef struct bitnode
{
char data;
struct bitnode *lchild,*rchild;
}*bitree;
bitree T;
typedef struct qnode
{
bitree deta;
struct qnode *next;
}*queueptr;
typedef struct
{
queueptr front;
queueptr rear;
}linkqueue;
linkqueue Q;
void layerorder(bitree t);
void enqueue(bitree t2);
bitree dequeue();
void main()
{
bitree t;
T=t=(bitnode*)malloc(sizeof(bitnode));
t->data='a';
t=t->lchild;
t=(bitnode*)malloc(sizeof(bitnode));
t->data='b';
t->lchild=NULL;
t->rchild=NULL;
t=T;
t=t->rchild;
t=(bitnode*)malloc(sizeof(bitnode));
t->data='c';
t->lchild=NULL;
t->rchild=NULL;
layerorder(T);
}

void layerorder(bitree t1)
{
bitree p;
Q.front=Q.rear=(queueptr)malloc(sizeof(qnode));
enqueue(t1);
while(Q.front!=Q.rear)
{
p=dequeue();
if(p->lchild)
enqueue(p->lchild);
if(p->rchild)
enqueue(p->rchild);
}
}
void enqueue(bitree t2)
{
queueptr q;
q=(queueptr)malloc(sizeof(qnode));
q->deta=t2;
q->next=NULL;
Q.rear->next=q;
Q.rear=q;
}
bitree dequeue()
{
queueptr q1;
bitree p2;
q1=Q.front->next;
p2=q1->deta;
Q.front->next=q1->next;
printf("%c",p2->data);
return(p2);
}