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;
    }
};
相关推荐
永远都不秃头的程序员(互关)18 分钟前
查找算法深入分析与实践:从线性查找到二分查找
数据结构·c++·算法
良木生香1 小时前
【数据结构-初阶】详解线性表(1)---顺序表
数据结构
CoderYanger1 小时前
C.滑动窗口——2762. 不间断子数组
java·开发语言·数据结构·算法·leetcode·1024程序员节
好风凭借力,送我上青云1 小时前
哈夫曼树和哈夫曼编码
c语言·开发语言·数据结构·c++·算法·霍夫曼树
秋深枫叶红2 小时前
嵌入式第三十篇——数据结构——哈希表
数据结构·学习·算法·哈希算法
✎ ﹏梦醒͜ღ҉繁华落℘2 小时前
编程基础--数据结构
数据结构·算法
mifengxing2 小时前
B树的定义以及插入和删除
数据结构·b树
sin_hielo2 小时前
leetcode 1523
数据结构·算法·leetcode
hakertop3 小时前
如何基于C#读取.dot图论文件并和QuickGraph联动
数据库·c#·图论
xu_yule3 小时前
数据结构(7)带头双向循环链表的实现
数据结构·链表