#include<iostream>
using namespace std;
#define maxSize 100
typedef struct BTNode
{
char data;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode, *BTree;
BTree creatTree();
void levelOrderBTree(BTNode *p);
int main()
{
BTree pTree = creatTree();
cout << "层序遍历:";
levelOrderBTree(pTree);
return 0;
}
BTree creatTree()
{//创建一颗二叉树
BTree pA = (BTNode *)malloc(sizeof(BTNode));
BTree pB = (BTNode *)malloc(sizeof(BTNode));
BTree pC = (BTNode *)malloc(sizeof(BTNode));
BTree pD = (BTNode *)malloc(sizeof(BTNode));
BTree pE = (BTNode *)malloc(sizeof(BTNode));
BTree pF = (BTNode *)malloc(sizeof(BTNode));
BTree pG = (BTNode *)malloc(sizeof(BTNode));
BTree pH = (BTNode *)malloc(sizeof(BTNode));
BTree pI = (BTNode *)malloc(sizeof(BTNode));
pA->data = 'A';
pB->data = 'B';
pC->data = 'C';
pD->data = 'D';
pE->data = 'E';
pF->data = 'F';
pG->data = 'G';
pH->data = 'H';
pI->data = 'I';
pA->lchild = pC;
pA->rchild = pB;
pC->lchild = pD;
pC->rchild = pE;
pB->rchild = pF;
pB->lchild = NULL;
pD->lchild = pG;
pD->rchild = NULL;
pE->lchild = NULL;
pE->rchild = pH;
pF->lchild = pI;
pF->rchild = NULL;
pG->lchild = pG->rchild = NULL;
pH->lchild = pH->rchild = NULL;
pI->lchild = pI->rchild = NULL;
return pA;
}
void levelOrderBTree(BTNode *p)
{
int front, rear;
BTNode *que[maxSize];//定义一个循环队列,用来记录将要访问的层次上的结点
front = rear = 0; BTNode *q;
if (p != NULL)
{
rear = (rear + 1) % maxSize;
que[rear] = p; //根结点入队
while (front != rear)
{//当队列不空的时候进行循环
front = (front + 1) % maxSize;
q = que[front]; //队头结点出队
cout << q->data;
if (q->lchild != NULL)
{ //如果它有左子树,则将左子树的根结点入队
rear = (rear + 1) % maxSize;
que[rear] = q->lchild;
}
if (q->rchild != NULL)
{ //如果它有右子树,则将右子树的根结点入队
rear = (rear + 1) % maxSize;
que[rear] = q->rchild;
}
}
cout << endl;
}
}