【力扣每日一题】力扣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;
    }
}
相关推荐
折哥的程序人生 · 物流技术专研2 小时前
Java面试85题图解版 · 特别篇:2026后端高频面试题复盘(算法底层逻辑+高并发架构设计全解析,附Java实战代码)
java·网络·数据库·算法·面试
一条泥憨鱼2 小时前
【Redis】数据类型和常用命令
java·数据库·redis·后端·缓存
云烟成雨TD3 小时前
Spring AI Alibaba 1.x 系列【78】沙箱(Sandbox)
java·人工智能·spring
程序员二叉3 小时前
【Java】 异常高频面试题精讲 | 易错点+对比总结
java·开发语言·面试
玖玥拾3 小时前
C/C++ 基础笔记(十四)多态与模板编程
c语言·c++·多态·模板
周航宇JoeZhou3 小时前
JB3-9-SpringAI(二)
java·ai·agent·多智能体·调度·智能体·观察
好家伙VCC3 小时前
Web Components主题热切换方案揭秘
java·前端
慕木沐3 小时前
Google ADK Java 1.0版本 核心机制与实战 Demo
java·开发语言·python
想吃火锅10053 小时前
【leetcode】14.最长公共前缀js
算法·leetcode·职场和发展
Roann_seo%3 小时前
C++文件操作完全指南:从文本读写到二进制文件处理
开发语言·c++