0
点赞
收藏
分享

微信扫一扫

二叉树的广度优先搜索


(一)基本思想

二叉树的广度优先搜索_二叉树

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

二叉树的广度优先搜索_搜索_02

具体步骤:
步骤:
(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


举报

相关推荐

0 条评论