二叉树的层序遍历

102. Binary Tree Level Order Traversal

广度优先搜索

将每个结点的层号记录下。

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:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(!root) return res;
        res.resize(2000);
        queue<tuple<TreeNode*,int>> Q;
        Q.push(make_tuple(root,0));
        tuple<TreeNode*,int> temp;
        int maxlevel = 0;
        while(!Q.empty()){
            temp = Q.front();
            res[get<1>(temp)].push_back(get<0>(temp)->val);
            if(get<1>(temp) > maxlevel) maxlevel = get<1>(temp);
            Q.pop();
            if(get<0>(temp)->left)
                Q.push(make_tuple(get<0>(temp)->left,get<1>(temp)+1));
            if(get<0>(temp)->right)
                Q.push(make_tuple(get<0>(temp)->right,get<1>(temp)+1));
        }
        res.resize(maxlevel+1);
        return res;
    }
};
相关推荐
syagain_zsx28 分钟前
算法基础篇 · 03 枚举(C++ 题解)
c++·算法·二进制·枚举
weixin_307779131 小时前
C++代码实现MATLAB中的ode23tb函数功能
开发语言·c++·算法·matlab
我是章汕呐2 小时前
地级市能源消耗量及消耗强度数据【2006-2023年】平衡面板
人工智能·经验分享·算法·回归
charliejohn2 小时前
计算机考研 408 数据结构 堆的插入与删除 堆排序
算法
老鱼说AI2 小时前
从点积到希尔伯特空间:向量内积的几何本质与大模型相似度度量
人工智能·深度学习·线性代数·算法·机器学习·数学建模
地平线开发者3 小时前
模型部署|如何解决算子约束
深度学习·算法·自动驾驶
Navigator_Z4 小时前
LeetCode //C - 1254. Number of Closed Islands
c语言·算法·leetcode
deepseek234 小时前
GPT-6 Astra 破解 FrontierMath 九年悬案拆解:调和熵投票规则反证核恒非空,局部搜索如何终结反例悬赏
人工智能·算法·ai agent
syagain_zsx4 小时前
算法基础篇 · 04 前缀和(C++ 题解)
c++·算法·前缀和
Logic1014 小时前
C语言/数据结构滑动窗口题解:替换k个字符后的最长连续相同字符子串(LeetCode 424)
c语言·数据结构·字符串·滑动窗口·时间复杂度·频率统计·算法题