层序遍历

首先我们先了解一下什么是层序遍历:

层序遍历:进行层序遍历时,对某一层的节点访问完后,再按照他们的访问次序对各个节点的左孩子和右孩子顺序访问,这样一层一层进行,先访问的节点其左右孩子也要先访问,这正好符合队列的操作特性。

二叉树的层序遍历算法:

#include <iostream>
#include <stdlib.h>
using namespace std;

/*树的节点*/
struct node
{
    node *lchild, *rchild; //左右孩子指针
    int value; //树节点数据
};

/*链队节点*/
struct Node
{
    Node *next;
    node *value;//树的节点地址
};

/*链队的类*/
class Queue
{
public:
    Queue();
    void EnQueue(node *T); //入队
    void Display(); //打印
    node *Front(); //返回上一个元素
    bool Empty();
private:
    Node *head;//队头指针
    Node *rear;//尾指针
};

/*判断链队是否为满*/
bool Queue::Empty()
{
    if (head == NULL)
        return false;
    else
        return true;
}

/*出队函数:队头指针向后移,返回先前的队头指针*/
node *Queue::Front()
{
    node *temp = head->value;
    head = head->next;
    return temp;
}

/*打印函数*/
void Queue::Display()
{
    if (head == NULL)
        return;
    Node *p = head;
    while (p)
    {
        cout << p->value << ' ';
        p = p->next;
    }
}

/*队列初始化*/
Queue::Queue()
{
    head = rear = NULL;
}

/*入队函数*/
void Queue::EnQueue(node *T)
{
    if (head == NULL)
    {
        head = new Node;
        head->value = T;
        head->next = NULL;
        rear = head;
    }
    else
    {
        Node *p = new Node;
        p->next = NULL;
        p->value = T;
        rear->next = p;
        rear = p;
    }
}

/*二叉树的类*/
class BITree
{
public:
    node* CreateTree(node *T);
    void LeverOrder(node *T);
private:
    Queue Q;
};

/*层序遍历*/
void BITree::LeverOrder(node *T)
{
    node *p = T;
    Q.EnQueue(p);
    while (Q.Empty())
    {
        p = Q.Front();
        cout << p->value << ' ';
        if (p->lchild)
            Q.EnQueue(p->lchild);
        if (p->rchild)
            Q.EnQueue(p->rchild);
    }
}

/*建立二叉树*/
node* BITree::CreateTree(node *T)
{
    int i;
    cin >> i;
    if (i == 0)
        T = NULL;
    else
    {
        T = new node;
        T->value = i;
        T->lchild = CreateTree(T->lchild); //递归建立左子树
        T->rchild = CreateTree(T->rchild);//递归建立右子树
    }
    return T; //返回根指针
}
int main()
{
    cout << "请输入你要输入的字符,按0结束:" << endl;
    node *T = NULL;
    BITree text; //定义一个二叉树
    T = text.CreateTree(T); //建立二叉树
    text.LeverOrder(T); //层序遍历
    getchar();
    getchar();
    return 0;
}

// 1 2 3 4 0 0 5 0 0 0 6 7 0 0 8 0 0

转载于:https://my.oschina.net/foreverwiner/blog/768270

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值