【力扣每日一题】力扣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;
    }
}
相关推荐
~|Bernard|1 小时前
在 PyCharm 里怎么“点鼠标”完成指令同样的运行操作
算法·conda
战术摸鱼大师1 小时前
电机控制(四)-级联PID控制器与参数整定(MATLAB&Simulink)
算法·matlab·运动控制·电机控制
Christo31 小时前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘
好家伙VCC2 小时前
数学建模模型 全网最全 数学建模常见算法汇总 含代码分析讲解
大数据·嵌入式硬件·算法·数学建模
皮皮林5513 小时前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
利刃大大3 小时前
【高并发内存池】五、页缓存的设计
c++·缓存·项目·内存池
weixin_456904273 小时前
Spring Boot 用户管理系统
java·spring boot·后端
趁你还年轻_3 小时前
异步编程CompletionService
java
DKPT3 小时前
Java内存区域与内存溢出
java·开发语言·jvm·笔记·学习
sibylyue3 小时前
Guava中常用的工具类
java·guava