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

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

相关推荐
AGV算法笔记13 分钟前
CVPR 2025 最新感知算法解读:GaussianLSS 如何用 Gaussian Splatting 重构 BEV 表示?
算法·重构·自动驾驶·3d视觉·感知算法·多视角视觉
勤劳的进取家1 小时前
数据链路层基础
网络·学习·算法
Advancer-1 小时前
第二次蓝桥杯总结(上)
java·算法·职场和发展·蓝桥杯
ん贤2 小时前
加密算法(对称、非对称、哈希、签名...)
算法·哈希算法
superior tigre2 小时前
78 子集
算法·leetcode·深度优先·回溯
天威?*2 小时前
bitset的数据结构用法
算法·动态规划
hoiii1873 小时前
粒子滤波跟踪系统 - 蒙特卡洛方法实现
算法
weisian1514 小时前
Java并发编程--47-分布式ID生成器:雪花算法(Snowflake)与时钟回拨问题
java·算法·时钟回拨·雪花算法id
itzixiao4 小时前
L1-066 猫是液体(5分)[java][python]
java·开发语言·python·算法
ytttr8734 小时前
MATLAB SIFT图像配准实现
算法·机器学习·matlab