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

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

相关推荐
点云SLAM20 小时前
Boost库中Math 模块的根搜索 / 根求解和示例
数学·算法·数值优化·根搜索 / 根求解和示例·函数根求解·boost模块
我搞slam20 小时前
EM Planner算法与代码解读
算法
CodeWizard~21 小时前
线性筛法求解欧拉函数以及欧拉反演
算法
45288655上山打老虎21 小时前
右值引用和移动语义
算法
liulilittle21 小时前
C++ 并发双阶段队列设计原理与实现
linux·开发语言·c++·windows·算法·线程·并发
无名修道院21 小时前
渗透测试新手面试高频 50 题:原理 + 标准答案(2025)- 第三篇
网络安全·面试·职场和发展·渗透测试·内网渗透·免杀
白狐_7981 天前
【项目实战】我用一个 HTML 文件写了一个“CET-6 单词斩”
前端·算法·html
Jasmine_llq1 天前
《P3811 【模板】模意义下的乘法逆元》
数据结构·算法·线性求逆元算法·递推求模逆元
尋有緣1 天前
力扣2292-连续两年有3个及以上的订单产品
leetcode·oracle·数据库开发
Jacob程序员1 天前
欧几里得距离算法-相似度
开发语言·python·算法