zoukankan      html  css  js  c++  java
  • BFS和DFS算法实现

    #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){}
    };
    
    void Create(BitNode *&root)
    {
        int key;
        cin >> key;
        if (key == -1)
            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);
    }

    BFS:广度优先算法,通过队列,左子树入队,右子树入队。

    DFS:深度优先算法,通过栈,右子树入栈,左子树入栈。

  • 相关阅读:
    Ubuntu 14.04 LTS 系统空间不足,输入密码后,无法进入桌面的解决办法
    语言代码表
    在WPS中删除整行的快捷键是什么?
    Google浏览器&插件
    Linux命令大全
    Python下载安装
    Tiobe最新编程语言排行
    windows 清理利器
    如何用VBA实现格式刷的功能?
    武侠音乐精装
  • 原文地址:https://www.cnblogs.com/EvansPudding/p/12607749.html
Copyright © 2011-2022 走看看