【力扣每日一题】力扣429N叉树的层序遍历

题目来源

力扣429N叉树的层序遍历

题目概述

给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。

思路分析

跟二叉树的层序遍历基本一致,只不过把向孩子节点列表添加左右节点该成了添加父节点的全部孩子节点。

代码实现

java实现

java 复制代码
public class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        // 结果列表
        List<List<Integer>> res = new ArrayList<>();
        // 父节点列表
        List<Node> parentList = new ArrayList<>();
        parentList.add(root);
        while (!parentList.isEmpty()) {
            // 本轮父节点转val
            List<Integer> temp = new ArrayList<>();
            // 孩子节点列表
            List<Node> sonList = new ArrayList<>();
            for (Node parent : parentList) {
                temp.add(parent.val);
                if (parent.children != null && parent.children.size() > 0) {
                    sonList.addAll(parent.children);
                }
            }
            res.add(temp);
            parentList = sonList;
        }
        return res;
    }
}

c++实现

cpp 复制代码
class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        // 结果列表
        vector<vector<int>> res;
        if (root == nullptr) {
            return res;
        }
        // 父节点列表
        vector<Node*> parent_list;
        parent_list.push_back(root);
        while (!parent_list.empty()){
            // 父节点转val
            vector<int> temp;
            // 孩子节点列表
            vector<Node*> son_list;
            for (auto parent : parent_list) {
                temp.push_back(parent->val);
                for (auto child : parent->children) {
                    son_list.push_back(child);
                }
            }
            parent_list = son_list;
            res.push_back(temp);
        }
        return res;
    }
}
相关推荐
毕设源码-朱学姐1 天前
【开题答辩全过程】以 爱心捐赠网站为例,包含答辩的问题和答案
java·eclipse
charlie1145141911 天前
精读C++20设计模式:行为型设计模式:中介者模式
c++·学习·设计模式·c++20·中介者模式
楼田莉子1 天前
Qt开发学习——QtCreator深度介绍/程序运行/开发规范/对象树
开发语言·前端·c++·qt·学习
尘觉1 天前
中秋节与 Spring Boot 的思考:一场开箱即用的团圆盛宴
java·spring boot·后端
逻辑留白陈1 天前
Adaboost进阶:与主流集成算法对比+工业级案例+未来方向
算法
Learn Beyond Limits1 天前
Mean Normalization|均值归一化
人工智能·神经网络·算法·机器学习·均值算法·ai·吴恩达
oioihoii1 天前
超越 std::unique_ptr:探讨自定义删除器的真正力量
c++
天选之女wow1 天前
【代码随想录算法训练营——Day28】贪心算法——134.加油站、135.分发糖果、860.柠檬水找零、406.根据身高重建队列
算法·leetcode·贪心算法
Gohldg1 天前
C++算法·贪心例题讲解
c++·数学·算法·贪心算法
Le1Yu1 天前
2025-10-7学习笔记
java·笔记·学习