二叉树的层次遍历

二叉树的遍历在之前写过的递归和非递归的形式都是通过访问一个子树在访问结点来完成的,有时候我们需要对树进行一层一层的遍历,这样就的遍历叫做层次遍历。

实现二叉树的层次遍历可以借助一个队列来进行实现,我们访问根结点,把它放入队列,如果队列中现在不为空,那么就把这个结点出队列,并且输出结点,在把它的左孩子结点和右孩子结点入队列。就这样进行循环直到队列为空停止,此时输出的结点就是层次遍历的顺序。

代码通过链式队列的辅助来实现:

#include<cstdio>
#include<malloc.h>
using namespace std;
typedef struct TREE
{
    char data;
    TREE *lchild,*rchild;
} TREE, *tree;                       //定义树结点结构
typedef struct node
{
    tree ch;
    node *next;
} node,*nodelist;                  //定义队列结点结构
typedef struct
{
    nodelist front;
    nodelist rear;
} linkqueue;                            //定义队列指针
//建树
tree createtree()
{
    char ch;
    tree T;
    scanf("%c",&ch);
    if(ch=='#')
        T=NULL;
    else
    {
        T=(tree)malloc(sizeof(TREE));
        T->data=ch;
        T->lchild = createtree();
        T->rchild = createtree();
    }
    return T;
}
//初始化一个带头结点的队列
void initqueue(linkqueue &q)
{
    q.front=q.rear=(nodelist)malloc(sizeof(node));
    q.front->next=NULL;
}
//入队列
void enqueue(linkqueue &q,tree p)
{
    nodelist s;
    int first=1;
    s=(nodelist)malloc(sizeof(node));
    s->ch=p;
    s->next=NULL;
    q.rear->next=s;
    q.rear=s;
}
//出队列
void dequeue(linkqueue &q,tree &p)
{
    char data;
    nodelist s;
    s=q.front->next;
    p=s->ch;
    data=p->data;
    q.front->next=s->next;
    if(q.rear==s)
        q.rear=q.front;
    free(s);
    printf("%c ",data);
}
//判断队列是否为空
int queueempty(linkqueue q)
{
    if(q.front->next==NULL)
        return 1;
    return 0;
}
//按层次遍历树中结点
void traverse(tree bt)
{
    linkqueue q;
    tree p;
    initqueue(q);
    p=bt;
    enqueue(q,p);
    while(queueempty(q)!=1)
    {
        dequeue(q,p);
        if(p->lchild!=NULL)
            enqueue(q,p->lchild);
        if(p->rchild!=NULL)
            enqueue(q,p->rchild);
    }
    printf("\n");
}
//主函数
int main()
{
    freopen("1.txt", "r", stdin);
    tree bt;
    bt = createtree();
    printf("按层次遍历树中结点其输出顺序为: \n");
    traverse(bt);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值