二叉树的广度优先搜索

作者: 海天一树X | 来源:发表于2017-09-03 09:11 被阅读79次

(一)基本思想

bitree.png

使用两个队列存放节点元素,队列1用来存放未遍历过的节点,队列2用来存放遍历的节点。

bitree-bfs.png

具体步骤:
步骤:
(1)把根结点,放到队列1中。见图(a)

(2)弹出队列1的中的队首元素,被弹出的元素放到队列2中。若该队首元素有子节点,按从到右的顺序加入到队列1中。见图(b)

(3)重复步骤2),见图(c)~图(h)

(4)整个过程结束。队列2中的元素顺序就是使用广度优先搜索方法所遍历的顺序。

(二)C++代码实现

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

struct node
{
    int data;
    node *left;
    node *right;
};

void bfs(int a[], int size)
{
    queue<node *> visited, unvisited;
    node nodes[size];
    node *current;
    
    // 构建二叉树
    for(int i = 0; i < size; i++)
    {
        nodes[i].data = a[i];
        // 左子节点
        int child = 2 * i + 1;
        if(child < size)
        {
            nodes[i].left = &nodes[child];
        }
        else
        {
            nodes[i].left = NULL;
        }
        
        // 右子节点
        child++;
        if(child < size)
        {
            nodes[i].right = &nodes[child];
        }
        else
        {
            nodes[i].right = NULL;
        }
    }
    
    // 先把第0个节点加到unvisited队列中
    unvisited.push(&nodes[0]);
    while (!unvisited.empty())
    {
        current = unvisited.front();
        unvisited.pop();

        if(NULL != current->left)
        {
            unvisited.push(current->left);
        }
        
        if(NULL != current->right)
        {
            unvisited.push(current->right);
        }
        
        visited.push(current);
        
        cout << current->data << "  ";        
    }
}

int main(int argc, const char * argv[])
{
    int a[] = {0, 1, 2, 3, 4, 5, 6};
    int size = sizeof(a)/sizeof(int);
    bfs(a, size);
    return 0;
}

运行结果:

 0  1  2  3  4  5  6



更多内容请关注微信公众号


wechat_344.jpg

相关文章

  • 101. 对称二叉树

    101. 对称二叉树 1.想法: A.深度优先搜索://TODO B.广度优选搜索:直接利用广度优先搜索:对每一层...

  • 5. 深度优先、广度优先

    1. 二叉树的深度优先遍历和广度优先遍历2. 深度优先搜索递归和非递归实现 深度优先(DFS):前序遍历 广度优先...

  • 14-深度优先搜索(Depth First Search)

    深度优先搜索(Depth First Search) 与广度优先搜索一样,在二叉树搜索部分,也有用到过类似于深度优...

  • 搜索

    一、深度优先搜索 图深度优先遍历、深度优先搜索算法求有权图两点最短路径 二、广度优先搜索 图广度优先遍历、广度优先...

  • 图的遍历

    结构 深度优先搜索 广度优先搜索

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

    一、深度优先搜索 二、广度优先搜索

  • 深度优先广度优先

    深度优先搜索 广度优先搜索(队列实现)

  • LeetCode广度、深度优先搜索

    广度优先搜索 广度优先搜索(也称宽度优先搜索,缩写BFS即即Breadth First Search)是连通图的一...

  • 5,DFS、BFS

    引用数据结构二叉树的概念:深度优先搜索类似前序遍历、广度优先搜索类似层次遍历 用遍历DOM为例来说明:深度的核心代...

  • 广度优先搜索算法

    上一篇简书小编分享了“深度优先搜索”算法,今天小编继续分享下“广度优先搜索”算法。 一、何为“广度优先搜索” 广度...

网友评论

    本文标题:二叉树的广度优先搜索

    本文链接:https://www.haomeiwen.com/subject/gqmdjxtx.html