二叉树的广度优先搜索

本文介绍了一种使用两个队列实现的二叉树广度优先遍历方法,并给出了详细的步骤说明与C++代码实现。通过此方法,可以有效地遍历二叉树的所有节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(一)基本思想

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值