二叉树的层序遍历

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;
    }
};
相关推荐
uhakadotcom29 分钟前
PyTorch 分布式训练入门指南
算法·面试·github
uhakadotcom33 分钟前
PyTorch 与 Amazon SageMaker 配合使用:基础知识与实践
算法·面试·github
Craaaayon1 小时前
Java八股文-List集合
java·开发语言·数据结构·list
uhakadotcom1 小时前
在Google Cloud上使用PyTorch:如何在Vertex AI上训练和调优PyTorch模型
算法·面试·github
wen__xvn1 小时前
c++STL入门
开发语言·c++·算法
明月看潮生2 小时前
青少年编程与数学 02-016 Python数据结构与算法 03课题、数组与链表
数据结构·python·青少年编程·编程与数学
苏卫苏卫苏卫3 小时前
【Python】数据结构练习
开发语言·数据结构·笔记·python·numpy·pandas
weisian1513 小时前
力扣经典算法篇-9-跳跃游戏(贪心算法,反向递推)
算法·leetcode·游戏
MCYH02064 小时前
C++抽卡模拟器
java·c++·算法·概率·原神
pystraf4 小时前
P10587 「ALFR Round 2」C 小 Y 的数 Solution
数据结构·c++·算法·线段树·洛谷