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

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

相关推荐
froyoisle4 分钟前
CSP 真题解析:[CSP-J 2020-T3] 表达式
c++·算法·csp·信息学·信奥赛
geats人山人海8 分钟前
算法好题 2026.7.18
算法
文祐16 分钟前
C++类之虚函数表没有虚继承的菱形继承
开发语言·c++·算法
Lumos18626 分钟前
51单片机从零到实战(8)——串口通信
算法
lvchaoq29 分钟前
this指向面试代码输出题目合集
javascript·面试·职场和发展
小帽子_1231 小时前
大功率 PCS 双环闭环控制算法原理与实现
算法
buhuizhiyuci2 小时前
【算法篇】位运算 —— 基础篇
java·数据库·算法
Black蜡笔小新2 小时前
算法训练完了怎么上线?DLTM→AIS→EasyGBS三步交付流水线
人工智能·算法
weixin_727535622 小时前
JVM 常见八股面试问答:深入底层原理
jvm·面试·职场和发展
sycmancia2 小时前
Qt——多线程与界面组件的通信
开发语言·qt·算法