二叉树的层次遍历

#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;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值