[力扣题解]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;
    }
};

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

相关推荐
凯瑟琳.奥古斯特9 分钟前
动态调优IoU提升OCR文本合并精度
开发语言·python·算法
布莱克60531 分钟前
A* 算法详解:从原理到实现
开发语言·c++·算法
段一凡-华北理工大学38 分钟前
高炉炼铁机器视觉与智能识别十八讲~系列文章15:可靠性篇:防误报、容错与识别系统的鲁棒性设计
人工智能·算法·机器学习·高炉大模型·高炉机器视觉·高炉炼铁模型开发
某林2121 小时前
局部路径规划器 DWB:速度采样与评分权重的取值分析
人工智能·算法·架构·机器人·技术复盘
AI职业加油站1 小时前
模数共振行动解读|大模型应用工程师证书,匹配行业 RAG/Agent 落地人才需求
人工智能·学习·算法·职场和发展·职场发展
lengxuenong2 小时前
树状数组 · 信息学学习手册2-离散化与逆序对
c++·学习·算法
琳达爱分享2 小时前
五个线程同时去换 token,四个被踢下线:刷新接口其实不是幂等的
后端·算法·架构
十二2 小时前
【洛谷题解】P1115 最大子段和(前缀和 + 维护最小前缀)
数据结构·c++·算法·蓝桥杯
Xin7702 小时前
LeetCode 46. 全排列(回溯法)
leetcode
renhongxia13 小时前
RAG检索增强生成:打通大模型与外部知识的通道
大数据·人工智能·算法