C++二叉树的层序遍历(广度优先搜索)借助 队列 实现

这篇博客详细讲解了如何使用C++和队列进行二叉树的层序遍历,涵盖了LeetCode上的多道相关题目,包括102.二叉树的层序遍历、107.二叉树的层序遍历II等。通过层次遍历模板代码,解决了不同场景下的问题,如计算最大深度、右视图、层平均值等。
摘要由CSDN通过智能技术生成

阅前须知

这篇博客是关于二叉树的层序遍历详解,但是不涉及二叉树的基本定义及原理。
通过队列实现二叉树的层序遍历的各类题型,总结出来二叉树层序遍历的模板C++代码。
个人认为非常有价值


可以直接点击每一道题的题目,直达Leetcode。
参考代码随想客

Leetcode 102.二叉树的层序遍历

class Solution {
   
public:
    vector<vector<int>> levelOrder(TreeNode* root) 
    {
   
        queue<TreeNode*> que;
        vector<vector<int>> res;
        
        if(root!=nullptr)
        {
   
            que.push(root);
        }
        while(!que.empty())
        {
   
            int size=que.size(); 
            vector<int> temp;  //每次都是新数组
            for(int i=0;i<size;i++)
            {
   
                TreeNode* node=que.front();  //因为每一次都会pop()掉,所以一直保持横向移动
                que.pop();  //pop()掉是为了同一层横向移动
                temp.push_back(node->val);
                if(node->left)
                {
   
                    que.push(node->left);
                }
                if(node->right)
                {
   
                    que.push(node->right);
                }
            }
            res.push_back(temp);
        }
        return res;
    }
};

Leetcode 107.二叉树的层序遍历Ⅱ

这道题和102相比,就多了最后一个reverse();

class Solution {
   
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) 
    {
   
        queue<TreeNode*> que;
        vector<vector<int>> res;
        if(root!=nullptr)
        {
   
            que.push(root);
        }
        while(!que.empty())
        {
   
            vector<int> temp;
            int size=que.size();
            for(int i=0;i<size;i++)
            {
   
                TreeNode* node=que.front();
                que.pop();
                temp.push_back(node->val);
                if(node->left)
                {
   
                    que.push(node->left);
                }
                if(node->right)
                {
   
                    que.push(node->right);
                }
            }
            res.push_back(temp);
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值