【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;
    }  
    }
相关推荐
AlfredZhao22 分钟前
用脚本按顺序执行初始化 DB 的 SQL 文件
linux
瑞克-桑切斯1 小时前
企业生产环境:https部署+nginx高可用(业务不中断)
linux·服务器·数据库
浩浩测试一下8 小时前
Linux 底层知识点 1
linux·运维·服务器
Escalating_xu9 小时前
【Linux 网络编程】TCP 跨平台实战:用 Windows 客户端访问 Linux 服务器
linux·服务器·网络
忆挽篱笙歌10 小时前
环境变量,本地变量
linux·运维·服务器
罗西的思考10 小时前
【Agentic RL】Dressage Staleness 控制深度分析
人工智能·算法·机器学习
quaer10 小时前
弗洛伊德算法--判圈法寻找环的入口O(n) O(1)
数据结构·算法
文丑颜不良啊12 小时前
LeetCode51~75题目解析
leetcode
高晶12 小时前
无乘法器实现LC二阶滤波器:基于移位运算的快速算法与四种精度推导
算法·设计模式·程序员
ysbfsy12 小时前
大数计算思路
算法