二叉树的层序遍历-力扣

本题是二叉树的层序遍历,通过一个队列来控制遍历的节点,二叉树每层的节点和上一层入队的节点个数是相同的,根据这一点编写循环条件。

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) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;
        queue<TreeNode*> que;

        if(root != nullptr){
            que.push(root);
        }
        while(!que.empty()){
            int size = que.size();
            vector<int> vec;
            for(int i = 0; i < size; i++){
                TreeNode* cur = que.front();
                que.pop();
                vec.push_back(cur->val);
                if(cur->left != nullptr){
                    que.push(cur->left);
                }
                if(cur->right != nullptr){
                    que.push(cur->right);
                }                
            }
            result.push_back(vec);
        }
        return result;
    }
};

使用递归的写法:层序遍历也是正向进行遍历,因此在到达新的一层是,首先为返回数组result添加一个容纳这一层元素的空数组,之后便可以向这个空数组添加本层的元素,添加完后,前往这个节点的左右子节点。

cpp 复制代码
class Solution {
public:
    void order(TreeNode* cur, vector<vector<int>>& result, int depth){
        if(cur == nullptr){
            return;
        }
        if(result.size() == depth){
            result.push_back(vector<int>());
        }
        result[depth].push_back(cur->val);
        order(cur->left, result, depth + 1);
        order(cur->right, result, depth + 1);
    }

    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;
        int depth = 0;
        order(root, result, depth);
        return result;
    }
};
相关推荐
巧克力味的桃子11 分钟前
学习笔记:查找数组第K小的数(去重排名)
笔记·学习·算法
星云POLOAPI16 分钟前
大模型API调用延迟过高?深度解析影响首Token时间的五大因素及优化方案
人工智能·python·算法·ai
88号技师21 分钟前
2026年1月一区SCI-波动光学优化算法Wave Optics Optimizer-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
程序员阿鹏43 分钟前
如何保证写入Redis的数据不重复
java·开发语言·数据结构·数据库·redis·缓存
明朝百晓生1 小时前
强化学习[chapter8] [page17] Value Function Methods
人工智能·算法
POLITE31 小时前
Leetcode 56.合并区间 JavaScript (Day 6)
算法·leetcode·职场和发展
历程里程碑1 小时前
滑动窗口秒解LeetCode字母异位词
java·c语言·开发语言·数据结构·c++·算法·leetcode
ghie90902 小时前
使用直接节点积分法进行无网格法2D悬臂梁计算
算法
Helibo442 小时前
2025年12月gesp3级题解
数据结构·c++·算法
p&f°2 小时前
垃圾回收两种算法
java·jvm·算法