btree.h
#ifndef BTREE_H_INCLUDED
#define BTREE_H_INCLUDED
#define MaxSize 100
typedef char ElemType;
typedef struct node
{
ElemType data; //数据元素
struct node *lchild; //指向左孩子
struct node *rchild; //指向右孩子
} BTNode;
void CreateBTNode(BTNode *&b,char *str); //由str串创建二叉链
BTNode *FindNode(BTNode *b,ElemType x); //返回data域为x的节点指针
BTNode *LchildNode(BTNode *p); //返回*p节点的左孩子节点指针
BTNode *RchildNode(BTNode *p); //返回*p节点的右孩子节点指针
int BTNodeDepth(BTNode *b); //求二叉树b的深度
void DispBTNode(BTNode *b); //以括号表示法输出二叉树
void DestroyBTNode(BTNode *&b); //销毁二叉树
#endif // BTREE_H_INCLUDED
btree.cpp
#include <stdio.h>
#include "btree.h"
void LevelOrder(BTNode *b)
{
BTNode *p;
BTNode *qu[MaxSize]; //定义环形队列,存放节点指针
int front,rear; //定义队头和队尾指针
front=rear=-1; //置队列为空队列
rear++;
qu[rear]=b; //根节点指针进入队列
while (front!=rear) //队列不为空
{
front=(front+1)%MaxSize;
p=qu[front]; //队头出队列
printf("%c ",p->data); //访问节点
if (p->lchild!=NULL) //有左孩子时将其进队
{
rear=(rear+1)%MaxSize;
qu[rear]=p->lchild;
}
if (p->rchild!=NULL) //有右孩子时将其进队
{
rear=(rear+1)%MaxSize;
qu[rear]=p->rchild;
}
}
}
int main()
{
BTNode *b;
CreateBTNode(b,"A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))");
printf("二叉树b: ");
DispBTNode(b);
printf("\n");
printf("层次遍历序列:\n");
LevelOrder(b);
DestroyBTNode(b);
return 0;
}