[力扣题解]102.二叉树的层序遍历

题目:102. 二叉树的层序遍历

代码

迭代法

cpp 复制代码
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        queue<TreeNode*> que;
        TreeNode* cur;
        int i, size;
        vector<vector<int>> result;
        
        if(root != NULL)
        {
            que.push(root);
        }
        else
        {
            return result;
        }

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

        return result;
    }
};

递归法

我引入了order,来记录递归调用的顺序,方便理解:

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:
    void Order(TreeNode* cur, int depth, vector<vector<int>>& result, int& order)
    {
        order++;
        cout << "order = " << order << ", ";
        if(cur == NULL)
        {
            cout << endl;
            return;
        }
        if(depth == result.size())
        {
            // 来到新的层
            result.push_back(vector<int> ());
        }
        cout << "depth = " << depth << ", val = " << cur->val << endl;
        result[depth].push_back(cur->val);
        Order(cur->left, depth + 1, result, order);
        Order(cur->right, depth + 1, result, order);
    }

    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;
        int depth = 0;
        int order = 0;
        Order(root, depth, result, order);
        return result;
    }
};

下面是第一个测试样例的输出:

相关推荐
程序员-King.4 小时前
day158—回溯—全排列(LeetCode-46)
算法·leetcode·深度优先·回溯·递归
月挽清风5 小时前
代码随想录第七天:
数据结构·c++·算法
小O的算法实验室5 小时前
2026年AEI SCI1区TOP,基于改进 IRRT*-D* 算法的森林火灾救援场景下直升机轨迹规划,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
小郭团队5 小时前
2_1_七段式SVPWM (经典算法)算法理论与 MATLAB 实现详解
嵌入式硬件·算法·硬件架构·arm·dsp开发
充值修改昵称5 小时前
数据结构基础:从二叉树到多叉树数据结构进阶
数据结构·python·算法
Deepoch6 小时前
Deepoc数学大模型:发动机行业的算法引擎
人工智能·算法·机器人·发动机·deepoc·发动机行业
浅念-6 小时前
C语言小知识——指针(3)
c语言·开发语言·c++·经验分享·笔记·学习·算法
Hcoco_me7 小时前
大模型面试题84:是否了解 OpenAI 提出的Clip,它和SigLip有什么区别?为什么SigLip效果更好?
人工智能·算法·机器学习·chatgpt·机器人
BHXDML7 小时前
第九章:EM 算法
人工智能·算法·机器学习
却道天凉_好个秋8 小时前
目标检测算法与原理(三):PyTorch实现迁移学习
pytorch·算法·目标检测