【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;
    }  
    }
相关推荐
我是koten9 小时前
【运维杂谈】K8s遇到Terminating的名称空间删除不了怎么办?(解决方案亲测有效)
linux·运维·服务器·云原生·kubernetes·k8s·名称空间
GoAI14 小时前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
Pniubi15 小时前
力扣54.螺旋矩阵
算法·leetcode·矩阵
2601_9679873716 小时前
安装 Redis 或 Redis Stack
linux·windows·redis·macos·安装
feng_you_ying_li16 小时前
linux之数据链路层
linux·网络·智能路由器
choumou_M17 小时前
算法_1:由浅入深学习快速排序QuickSort
学习·算法·排序算法
GeW18 小时前
高端化走到深处,是数据库和Linux的事
linux
Coder_Shenshen18 小时前
罗克韦尔ACD工程归档离线变量树解析
算法·c#
程序员初一19 小时前
Linux 远程桌面有四种做法
linux·ssh