leetcode102 二叉树的层次遍历 使用队列实现二叉树广度优先遍历

借用一个辅助数据结构即队列来实现,队列先进先出,符合一层一层遍历的逻辑,而用栈先进后出适合模拟深度优先遍历也就是递归的逻辑。

而这种层序遍历方式就是图论中的广度优先遍历,只不过我们应用在二叉树上

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <vector>
#include <queue>

using namespace std;

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;  // 存储最终结果
        if (root == nullptr) {
            return result;  // 空树直接返回
        }
        
        queue<TreeNode*> q;  // 创建队列用于BFS
        q.push(root);  // 根节点入队
        
        while (!q.empty()) {
            int levelSize = q.size();  // 当前层的节点数
            vector<int> currentLevel;  // 存储当前层的节点值
            
            // 处理当前层的所有节点
            for (int i = 0; i < levelSize; ++i) {
                TreeNode* currentNode = q.front();  // 取出队首节点
                q.pop();  // 出队
                currentLevel.push_back(currentNode->val);  // 存储节点值
                
                // 将左右子节点入队(如果存在)
                if (currentNode->left != nullptr) {
                    q.push(currentNode->left);
                }
                if (currentNode->right != nullptr) {
                    q.push(currentNode->right);
                }
            }
            
            result.push_back(currentLevel);  // 将当前层加入结果
        }
        
        return result;
    }
};
相关推荐
xin007hoyo2 小时前
算法笔记.染色法判断二分图
数据结构·笔记·算法
__lost6 小时前
C++ 解决一个简单的图论问题 —— 最小生成树(以 Prim 算法为例)
算法·图论·最小生成树·prim算法
wuqingshun3141597 小时前
蓝桥杯 11. 打印大X
数据结构·算法·职场和发展·蓝桥杯·深度优先
wuqingshun3141598 小时前
蓝桥杯 2. 确定字符串是否是另一个的排列
数据结构·c++·算法·职场和发展·蓝桥杯
长沙火山9 小时前
9.ArkUI List的介绍和使用
数据结构·windows·list
AAAA劝导tx10 小时前
List--链表
数据结构·c++·笔记·链表·list
格格Code10 小时前
八大排序——冒泡排序/归并排序
数据结构·算法·排序算法
fantasy_410 小时前
LeetCode238☞除自身以外数组的乘积
java·数据结构·python·算法·leetcode
Phoebe鑫12 小时前
数据结构每日一题day12(链表)★★★★★
数据结构·算法·链表
八股文领域大手子12 小时前
深入浅出限流算法(三):追求极致精确的滑动日志
开发语言·数据结构·算法·leetcode·mybatis·哈希算法