【算法题】分层遍历二叉树

  • 使用双队列方式:一个队列表示当前层,一个队列表示下一层,
    换层时交换指向两队列的指针

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

struct Tree
{
    double value;
    Tree* left;
    Tree* right;
};

void Print(Tree* root)
{
    if (root == NULL)
        return;

    queue<Tree*> queue_current;
    queue<Tree*> queue_next;

    auto * p_current = &queue_current;
    auto * p_next = &queue_next;

    Tree* p = root;
    p_next->push(p);

    while (!(*p_next).empty())
    {
        std::swap(p_current, p_next);
        while (!(*p_current).empty())
        {
            p = p_current->front();
            p_current->pop();
            cout << p->value << " ";
            if (p->left != NULL)
            {
                p_next->push(p->left);
            }
            if (p->right != NULL)
            {
                p_next->push(p->right);
            }
        }
        cout << endl;
    }
}

int main()
{
    Tree root;
    Tree node1_1;
    Tree node1_2;
    Tree node2_1;
    Tree node2_2;
    Tree node2_3;
    Tree node3_1;
    Tree node3_2;
    Tree node3_3;
    Tree node3_4;

    root.value = 0;
    node1_1.value = 1.1;
    node1_2.value = 1.2;
    node2_1.value = 2.1;
    node2_2.value = 2.2;
    node2_3.value = 2.3;
    node3_1.value = 3.1;
    node3_2.value = 3.2;
    node3_3.value = 3.3;
    node3_4.value = 3.4;

    root.left = &node1_1;
    root.right = &node1_2;

    node1_1.left = &node2_1;
    node1_1.right = &node2_2;

    node1_2.left = &node2_3;
    node1_2.right = NULL;

    node2_1.left = &node3_1;
    node2_1.right = &node3_2;

    node2_2.left = NULL;
    node2_2.right = NULL;

    node2_3.left = &node3_3;
    node2_3.right = &node3_4;

    node3_1.left = NULL;
    node3_1.right = NULL;

    node3_2.left = NULL;
    node3_2.right = NULL;

    node3_3.left = NULL;
    node3_3.right = NULL;

    node3_4.left = NULL;
    node3_4.right = NULL;

    Print(&root);

    return 0;
}

  • 使用单队列
    每一层,使用一个变量记录该层的结点个数,也就是队列的当前长度,然后依次在队列中访问该层的结点(将队列中len个元素出队列),并将下一层加入队列。
void Print(Tree* pRoot)
{
    queue<Tree*> q;
    if (!pRoot) return;

    q.push(pRoot);

    while (!q.empty())
    {
        int len = q.size();
        while (len--)
        {
            Tree* tem = q.front();
            q.pop();

            cout << tem->value << " ";

            if (tem->left) q.push(tem->left);
            if (tem->right) q.push(tem->right);
        }
        cout << endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值