二叉树的广度优先搜索

来源:互联网 发布:夏米尔火花机简单编程 编辑:程序博客网 时间:2024/05/19 05:30

(一)基本思想

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
阅读全文
1 0
原创粉丝点击