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;
    }
};
相关推荐
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1231 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1122 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19432 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww2 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚2 天前
[数据结构] 排序
数据结构
睡不醒的kun2 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌2 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long2 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn2 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap