数据结构复习(层次遍历)

编写按层次顺序(同一层自左至右)遍历二叉树的算法。

要求实现下列函数:
void LevelOrder(BiTree bt, char *ss);
/* travel BiTree bt by level, Return result by ss. */

二叉链表类型定义:
typedef char TElemType;   // 设二叉树的元素为char类型
typedef struct BiTNode {
    TElemType data;
    BiTNode  *lchild, *rchild;
} BiTNode, *BiTree;

可用队列类型Queue的相关定义:
typedef BiTree QElemType; // 设队列元素为二叉树的指针类型
Status InitQueue(Queue &Q);
Status EnQueue(Queue &Q, QElemType e);
Status DeQueue(Queue &Q, QElemType &e);
Status GetHead(Queue Q, QElemType &e);
Status QueueEmpty(Queue Q);

提示:可将遍历元素的值(字符)依次置入ss,并最后以'\0'结尾。
也可以用下列字符串函数产生ss:
int sprintf(char *buffer, char *format [, argument, ...]);
char *strcat(char *dest, char *src);

void LevelOrder(BiTree bt, char *ss)
/* travel BiTree bt by level, Return result by ss. */
{
    Queue q;
    char *p=ss;
    BiTree pb=bt;
    if(!bt)
        return;
    InitQueue(q);
    EnQueue(q,pb);
    while(pb||!QueueEmpty(q)){
        DeQueue(q,pb);
        if(pb){
            *p++=pb->data;
            EnQueue(q,pb->lchild);
            EnQueue(q,pb->rchild);
        }       
    }
    *p='\0';
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值