【力扣每日一题】力扣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;
    }
}
相关推荐
玉树临风ives4 分钟前
atcoder ABC 452 题解
数据结构·算法
feifeigo12327 分钟前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
java1234_小锋36 分钟前
Java高频面试题:Springboot的自动配置原理?
java·spring boot·面试
fengfuyao9851 小时前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法
末央&1 小时前
【天机论坛】项目环境搭建和数据库设计
java·数据库
枫叶落雨2222 小时前
ShardingSphere 介绍
java
花花鱼2 小时前
Spring Security 与 Spring MVC
java·spring·mvc
无敌昊哥战神2 小时前
深入理解 C 语言:巧妙利用“0地址”手写 offsetof 宏与内存对齐机制
c语言·数据结构·算法
小白菜又菜2 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
Proxy_ZZ02 小时前
用Matlab绘制BER曲线对比SPA与Min-Sum性能
人工智能·算法·机器学习