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;
    }
};
相关推荐
小指纹3 小时前
河南萌新联赛2025第(四)场【补题】
数据结构·c++·算法·macos·objective-c·cocoa·图论
Y4090013 小时前
List、ArrayList 与顺序表
数据结构·笔记·list
设计师小聂!5 小时前
力扣热题100------136.只出现一次的数字
数据结构·算法·leetcode
flashlight_hi6 小时前
LeetCode 分类刷题:2824. 统计和小于目标的下标对数目
javascript·数据结构·算法·leetcode
穆霖祎9 小时前
数据结构(4)
数据结构
秋难降9 小时前
LeetCode——迭代遍历算法
数据结构·算法·排序算法
yanxing.D9 小时前
考研408_数据结构笔记(第四章 串)
数据结构·笔记·考研·算法
啊阿狸不会拉杆10 小时前
《算法导论》第 7 章 - 快速排序
开发语言·数据结构·c++·算法·排序算法
John.Lewis11 小时前
C语言数据结构(4)单链表专题2.单链表的应用
c语言·数据结构·链表
冬夜戏雪11 小时前
java学习 73矩阵置零 54螺旋矩阵 148排序链表
数据结构·算法·矩阵