【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;
    }  
    }
相关推荐
hweiyu008 分钟前
Linux命令:nmtui
linux
knight_9___10 分钟前
大模型project面试4
人工智能·python·深度学习·算法·面试·agent
l1t15 分钟前
DeepSeek总结的欢迎来到 ORDER BY 丛林
数据库·算法
谙弆悕博士15 分钟前
【附C源码】二叉搜索树的C语言实现
c语言·开发语言·数据结构·算法·二叉树·项目实战·数据结构与算法
MY_TEUCK18 分钟前
【2026最新Linux虚拟机安装】Linux 虚拟机安装VMware 17 + CentOS 7
linux·运维·centos
Rust研习社25 分钟前
Ubuntu 全面拥抱 Rust 后,我意识到 Rust 社区要变了
linux·服务器·开发语言·后端·ubuntu·rust
Shingmc325 分钟前
【Linux】传输层协议TCP
linux·网络·tcp/ip
宵时待雨29 分钟前
回溯算法专题2:二叉树中的深搜
开发语言·数据结构·c++·笔记·算法·深度优先
刀法如飞35 分钟前
JavaScript 数组去重的 20 种实现方式,学会用不同思路解决问题
前端·javascript·算法
洛水水43 分钟前
【力扣100题】46.单词拆分
算法·leetcode·职场和发展