#define OVERFLOW -2
#define NULL_TREE '.'
#define MAXSIZE 50
typedef char TElemType;
typedef struct BiTNode {
TElemType data; // 数据域
struct BiTNode* lchild, * rchild; // 左右孩子指针
}BiTNode, * BiTree;
typedef BiTree ElemType;
// 循环顺序队列
typedef struct SqQueue {
ElemType data[MAXSIZE];
int front, rear;
}SqQueue;
void InitQueue(SqQueue& Q) {
Q.front = 0;
Q.rear = Q.front;
}
bool isEmpty(SqQueue Q) {
if (Q.rear == Q.front) return true;
else return false;
}
bool EnQueue(SqQueue& Q, ElemType x) {
if ((Q.rear + 1) % MAXSIZE == Q.front) return false;
Q.data[Q.rear] = x;
Q.rear = (Q.rear + 1) % MAXSIZE;
return true;
}
bool DeQueue(SqQueue& Q, ElemType& x) {
if (Q.rear == Q.front) return false;
x = Q.data[Q.front];
Q.front = (Q.front + 1) % MAXSIZE;
return true;
}
// 建二叉树
void CreateBiTree(BiTree& T) {
// 按照先序次序输入二叉树中结点的值, '.'表示空树
char ch;
scanf(" %c", &ch);
if (ch == NULL_TREE) T = NULL;
else {
if (!(T = (BiTNode*)malloc(sizeof(BiTNode)))) exit(OVERFLOW); // 内存空间不够,退出程序
T->data = ch;
CreateBiTree(T->lchild); // 递归构造左子树
CreateBiTree(T->rchild); // 递归构造右子树
}
}
// 二叉树的层次遍历
void LevelOrder(BiTree T){
SqQueue Q;
InitQueue(Q); // 初始化辅助队列
EnQueue(Q, T); // 根结点入队列
BiTree p;
while (!isEmpty(Q)) {
DeQueue(Q, p); // 队头结点出队列
visit(p); // 访问此结点
if (p->lchild != NULL)
EnQueue(Q, p->lchild); // 将此结点的左孩子入队列
if (p->rchild != NULL)
EnQueue(Q, p->rchild); // 将此结点的右孩子入队列
}
}
int main() {
BiTree btree;
/*
输入: A B E . . C . . .
输出:
先序: A B E C
中序: E B C A
后序: E C B A
层次: A B E C
*/
CreateBiTree(btree); // 建树
// 层次遍历
LevelOrder(btree); printf("\n");
return 0;
}
二叉树的层次遍历
最新推荐文章于 2024-09-08 20:07:18 发布