树的前中后序遍历和层次遍历

遍历规则

  • 前序遍历:根结点 ---> 左子树 ---> 右子树

  • 中序遍历:左子树---> 根结点 ---> 右子树

  • 后序遍历:左子树 ---> 右子树 ---> 根结点

  • 层次遍历:只需按层次遍历即可

注:

1.前序、中序、后序属于深度优先遍历(使用递归较为方便),层次遍历为广度优先遍历(一般实现需要借助其他数据结构的支撑,如下面的队列等)。
2.中序遍历有个小技巧:对于给定的树,可以画垂线,从左到右即为中序遍历的次序。

代码实现

#include <iostream>
#include <stack>
#include <queue>

using namespace std;

struct BitreeNode
{
    int data;
    struct BitreeNode *lchild, *rchild;
};

void InitTreeNode(BitreeNode &t, int data, BitreeNode *lchild, BitreeNode *rchild)
{
    t.data = data;
    t.lchild = lchild;
    t.rchild = rchild;
}

//前序
void PreOrder(BitreeNode *t)
{
    if (t != nullptr)
    {
        cout << t->data << " ";
        PreOrder(t->lchild);
        PreOrder(t->rchild);
    }
}
//中序
void Inorder(BitreeNode *t)
{
    if (t != nullptr)
    {
        Inorder(t->lchild);
        cout << t->data << " ";
        Inorder(t->rchild);
    }
}
//后序
void PostOrder(BitreeNode *t)
{
    if (t != nullptr)
    {
        PostOrder(t->lchild);
        PostOrder(t->rchild);
        cout << t->data << " ";
    }
}

//层次遍历
void LevelOrder(BitreeNode *t)
{
    queue<BitreeNode *> q;
    BitreeNode *p;
    q.push(t);


    while (!q.empty())
    {
        p = q.front();
        q.pop();
        cout << p->data << " ";
        if (p->lchild != nullptr)
            q.push(p->lchild);
        if (p->rchild != nullptr)
            q.push(p->rchild);
    }
}

int main()
{
    BitreeNode t1, t2, t3, t4, t5, t6, t7;

    InitTreeNode(t4, 4, nullptr, nullptr);
    InitTreeNode(t5, 5, nullptr, nullptr);
    InitTreeNode(t6, 6, nullptr, nullptr);
    InitTreeNode(t7, 7, nullptr, nullptr);
    InitTreeNode(t2, 2, &t4, &t5);
    InitTreeNode(t3, 3, &t6, &t7);
    InitTreeNode(t1, 1, &t2, &t3);

    //层次遍历
    LevelOrder(&t1);
    cout << endl;
    //前序遍历
    PreOrder(&t1);
    cout << endl;
    //中序遍历
    Inorder(&t1);
    cout << endl;
    //后续遍历
    PostOrder(&t1);
    cout << endl;
    system("pause");
    return 0;
}

运行测试:

参考:
https://blog.csdn.net/invisible_sky/article/details/80816797

猜你喜欢

转载自www.cnblogs.com/clwsec/p/11569686.html