【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;
    }  
    }
相关推荐
摇滚侠10 小时前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
通信小呆呆11 小时前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
bush411 小时前
嵌入式linux学习记录十四、术语
linux·嵌入式
benben04411 小时前
强化学习之DQN算法族(基于gymnasium开发)
算法
载数而行52011 小时前
Linux 11 动态监控指令top
linux
何以解忧,唯有..12 小时前
Go语言循环语句详解:for、range与循环控制
开发语言·算法·golang
不会C语言的男孩12 小时前
Linux 系统编程 · 第 8 章:进程基础
linux·c语言
古城小栈13 小时前
Unix 与 Linux 异同小叙
linux·服务器·unix
想吃火锅100513 小时前
【leetcode】88.合并两个有序数组js
算法