【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;
    }  
    }
相关推荐
小欣加油6 小时前
leetcode 912 排序数组(归并排序)
数据结构·c++·算法·leetcode·排序算法
禁默6 小时前
Linux 之从硬件硬盘到文件系统的全面过渡
linux·运维·服务器
山河君7 小时前
webrtc之高通滤波——HighPassFilter源码及原理分析
算法·音视频·webrtc·信号处理
星辰大海的精灵7 小时前
SpringBoot与Quartz整合,实现订单自动取消功能
java·后端·算法
塵觴葉7 小时前
Linux内核网络的连接跟踪conntrack简单分析
linux·网络·conntrack
data myth7 小时前
力扣1210. 穿过迷宫的最少移动次数 详解
算法·leetcode·职场和发展
m0_464608267 小时前
监控 Linux 服务器资源
linux
惯导马工7 小时前
【论文导读】AI-Assisted Fatigue and Stamina Control for Performance Sports on IMU-Gene
深度学习·算法
tongsound7 小时前
ros2 lifcycle介绍
linux·c++
☆璇7 小时前
【Linux】Linux环境基础开发工具使用
linux·运维·服务器