二叉树的层序遍历

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;
    }
};
相关推荐
J2虾虾5 分钟前
C语言 typedef 用法
c语言·数据结构·算法
hunterkkk(c++)13 分钟前
线段树例题
算法
故渊at23 分钟前
第二板块:Android 四大组件标准化学理 | 第七篇:Activity 页面载体与任务栈算法
android·算法·生命周期·activity·任务栈
兰令水30 分钟前
leecodecode【区间DP+树形DP】【2026.6.10打卡-java版本】
java·算法·leetcode
budingxiaomoli1 小时前
二叉树中的深搜
数据结构
weixin199701080161 小时前
[特殊字符] 1688开放平台API Sign签名算法详解(Java / Python / PHP 实现)
java·python·算法
断点之下1 小时前
数据结构从零开始④:堆——一种特殊的完全二叉树(附堆排序、TopK问题)
数据结构
WL学习笔记1 小时前
顺序表详解
c语言·数据结构
sugar__salt1 小时前
深入吃透前端线性数据结构:数组、栈、队列、链表核心原理与实战
前端·数据结构·链表