二叉树的层序遍历
二叉树的节点、队列节点,队列
//二叉树的节点
typedef struct BiTNode {
char data;
BiTNode* lchild, * rchild;
}BiTNode,*BiTree;
//链式队列节点
typedef struct LinkNode {
BiTNode* data;
LinkNode* next;
}LinkNode;
typedef struct {
LinkNode* front, * rear;//队头队尾
}LinkQueue;
1.初始化
void InitQueue(LinkQueue& Q) {
//初始化时,front,rear都指向头节点
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
Q.front->next = NULL;
}
2.判空
void InitQueue(LinkQueue& Q) {
//初始化时,front,rear都指向头节点
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
Q.front->next = NULL;
}
3.入队
void EnQueue(LinkQueue& Q,BiTNode* p) {
LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode));
s->data = p;
s->next = NULL;
Q.rear->next = s;
Q.rear = s;
}
4.出队
bool DeQueue(LinkQueue& Q, BiTNode* p) {
if (Q.front == Q.rear)
return false; //空队
LinkNode* x = Q.front->next;
p = x->data;
Q.front = x->next;
if (x == Q.rear) {
Q.rear = Q.front;
}
return true;
}
5.访问
void visit(BiTree p) {
printf("%c", p->data);
}
6.层序遍历
void LevelOrder(BiTNode* T) {
LinkQueue Q;
InitQueue(Q);
BiTree p=(BiTNode*)malloc(sizeof(BiTNode));
EnQueue(Q, T);
while (!IsEmpty(Q)) {
DeQueue(Q, p);
visit(p);
if (p->lchild != NULL)
EnQueue(Q, p->lchild);
if (p->rchild != NULL)
EnQueue(Q, p->rchild);
}
}