【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;
    }  
    }
相关推荐
菜地里的小菜鸟3 小时前
将linux程序打成.run包
linux·将linux程序打成run包·运维自动安装包
圣光SG5 小时前
Java操作题练习(七)
java·开发语言·算法
晚风吹长发6 小时前
Docker基础——Docker Network(网络详解)
linux·运维·网络·ubuntu·docker·容器
Cx330_FCQ6 小时前
Tmux使用
服务器·git·算法
高磊20057 小时前
LVS(Linux virual server)
linux·服务器·lvs
拳里剑气7 小时前
C++算法:多源BFS
c++·算法·宽度优先·多源bfs
ysa0510308 小时前
【板子】短序列dp(换成维护更小常数维度的dp)
c++·笔记·算法·板子
shwill1238 小时前
PID 算法(三)--- 增量 PID ↔ 单神经元 PID 等价映射
linux·算法
执笔画流年呀9 小时前
Linux搭建Java项目部署环境
java·linux·运维
Sisphusssss9 小时前
香橙派5plus GPIO
linux·python·ubuntu