二叉树的遍历(C++、STL)

之前没有使用C++的STL,写二叉树的遍历的时候基本都是选择用递归来实现,了解了C++标准模板库中的stack和queue后,发现遍历二叉树更加简单了,下面给出实例代码,通过实际验证发现这种方法很简洁,很方便

#include <vector>
#include <iostream>
#include <stack>
#include <queue>
using namespace std;

struct BitNode
{
    int data;
    BitNode *left, *right;
    BitNode(int x) :data(x), left(0), right(0){}
};

//创建二叉树函数,实际上安装先序遍历的方式来创建的,如果没有左(右)子数,则输入0
void Create(BitNode *&root)
{
    int key;
    cin >> key;
    if (key == 0)
        root = NULL;
    else
    {
        root = new BitNode(key);
        Create(root->left);
        Create(root->right);
    }
}

void PreOrderTraversal(BitNode *root)
{
    if (root)
    {
        cout << root->data << " ";
        PreOrderTraversal(root->left);
        PreOrderTraversal(root->right);
    }
}

//深度优先搜索
//利用栈,现将右子树压栈再将左子树压栈
void DepthFirstSearch(BitNode *root)
{
    stack<BitNode*> nodeStack;
    nodeStack.push(root);
    while (!nodeStack.empty())
    {
        BitNode *node = nodeStack.top();
        cout << node->data << ' ';
        nodeStack.pop();
        if (node->right)
        {
            nodeStack.push(node->right);
        }
        if (node->left)
        {
            nodeStack.push(node->left);
        }
    }
}

//广度优先搜索
void BreadthFirstSearch(BitNode *root)
{
    queue<BitNode*> nodeQueue;
    nodeQueue.push(root);
    while (!nodeQueue.empty())
    {
        BitNode *node = nodeQueue.front();
        cout << node->data << ' ';
        nodeQueue.pop();
        if (node->left)
        {
            nodeQueue.push(node->left);
        }
        if (node->right)
        {
            nodeQueue.push(node->right);
        }
    }
}

int  main()
{
    BitNode *root = NULL;
    Create(root);
    //前序遍历
    PreOrderTraversal(root);
    //深度优先遍历
    cout << endl << "dfs" << endl;
    DepthFirstSearch(root);
    //广度优先搜索
    cout << endl << "bfs" << endl;
    BreadthFirstSearch(root);
}

    原文作者:huasir_hit
    原文地址: https://blog.csdn.net/huasir_hit/article/details/75943167
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞