深度优先搜索和广度优先搜索

#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);
        cout << key << "'s left...\n";
        Create(root->left);
        cout << key << "'s right...\n";
        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);
}


[xiongli@localhost data_struct]$ ./a.out


10


10's left...
99
99's left...
10
10's left...
-1
10's right...
-1
99's right...
29
29's left...
-1
29's right...
-1
10's right...
99
99's left...
82
82's left...
102
102's left...
-1
102's right...
-1
82's right...
-1
99's right...
-1
10 99 10 29 99 82 102 
dfs
10 99 10 29 99 82 102 
bfs
10 99 99 10 29 82 102

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值