经典算法之层序遍历二叉树

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值