【LeetCode-中等题】429. N 叉树的层序遍历

文章目录

题目

方法一:二叉树的层序遍历的扩展

思路和二叉树的层序遍历一样,这一题的关键在于取出每个节点的孩子

java 复制代码
for(int j = 0;j<root.children.size();j++)//取出所有当前节点的所有孩子节点放到队列中
    queue.offer(root.children.get(j));
或者
for(Node node:root.children)//取出所有当前节点的所有孩子节点放到队列中
    queue.offer(node);
java 复制代码
class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        List<Integer> res = null;
        List<List<Integer>> zres = new ArrayList<>();
            if(root == null) return zres;
            Deque<Node> queue = new LinkedList<>();
            queue.offer(root);
            while(!queue.isEmpty()){
                    int size = queue.size();
                    res = new ArrayList<>();
                    for(int i =0;i<size;i++){
                        root=queue.poll();
                        res.add(root.val);
                        for(int j = 0;j<root.children.size();j++)//取出所有当前节点的所有孩子节点放到队列中
                            queue.offer(root.children.get(j));
                    }
                    zres.add(res);
            }
            return zres;
    }  
    }
相关推荐
小-黯13 分钟前
Linux桌面入口文件.desktop文件内容格式
linux·运维·服务器
CheungChunChiu1 小时前
Flutter 在嵌入式开发的策略与生态
linux·flutter·opengl
菜鸟233号1 小时前
力扣213 打家劫舍II java实现
java·数据结构·算法·leetcode
十五年专注C++开发1 小时前
CMake基础: 在release模式下生成调试信息的方法
linux·c++·windows·cmake·跨平台构建
不会代码的小猴1 小时前
Linux环境编程第三天笔记
linux·笔记
狐571 小时前
2026-01-18-LeetCode刷题笔记-1895-最大的幻方
笔记·算法·leetcode
~光~~1 小时前
【嵌入式linux学习】04_Pinctrl 和 GPIO子系统
linux·rk3588·嵌入式linux
Q741_1471 小时前
C++ 队列 宽度优先搜索 BFS 力扣 662. 二叉树最大宽度 每日一题
c++·算法·leetcode·bfs·宽度优先
Pluchon1 小时前
硅基计划4.0 算法 动态规划进阶
java·数据结构·算法·动态规划
475.352 小时前
linux-journal日志清理
linux·运维·服务器