【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;
    }  
    }
相关推荐
在书中成长33 分钟前
HarmonyOS 小游戏《对战五子棋》开发第18篇 - 棋盘设计
算法·harmonyos
Frostnova丶40 分钟前
(12)LeetCode 76. 最小覆盖子串
算法·leetcode·职场和发展
阿成学长_Cain1 小时前
Linux telinit 命令详解:运行级别切换|关机重启|系统维护一站式掌握
linux·运维·前端·网络
灯澜忆梦1 小时前
GO_函数_1
算法
言乐61 小时前
Python实现建造微服务商城后台
开发语言·python·算法·微服务·架构
凉云生烟2 小时前
机器学习 02- KNN算法
人工智能·算法·机器学习
wabs6662 小时前
关于动态规划【力扣583.两个字符串的删除操作的思考】
算法·leetcode·动态规划
可编程芯片开发2 小时前
空气流量和空气压力参数解耦系统simulink建模与仿真
算法
qeen872 小时前
【Linux】指令补充与shell的简单介绍
linux·运维·服务器
_Doubletful2 小时前
妙用位运算:解构汉明距离至100%(提供分析与多解)
c语言·算法·leetcode