【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;
    }  
    }
相关推荐
远航计算机2 分钟前
豆包GEO算法实证:引用池到答案之间,还有8.3%入选与13%失配两道关
人工智能·深度学习·算法
Julien200412 分钟前
管理机密(二)
linux·运维·服务器·学习方法
我是章汕呐37 分钟前
省级碳排放量计算【1995-2024年】 含原始数据和过程 10种能源
人工智能·经验分享·算法·能源
絲唸1 小时前
可信机器学习与对抗鲁棒性:温度读数有误差,温室的高温判定还能信吗?
人工智能·python·深度学习·神经网络·算法·机器学习·机器人
Huangjin007_1 小时前
【Linux 系统篇(四十四)】线程(五):线程互斥:从共享资源到互斥锁
linux·运维·服务器
圣保罗的大教堂1 小时前
leetcode 3884. 双端字符匹配 简单
leetcode
xiangyun612 小时前
Ubuntu 网络排障决策树(5):SYN 到了网卡,为什么既没有 SYN-ACK 也没有 RST
linux·运维·服务器·网络·安全·ubuntu
无忧.芙桃2 小时前
Linux系统编程(八):进程
linux·运维·服务器
码农爱学习2 小时前
从零做一个MCP:以Ubuntu内存分析为例
linux·ubuntu·mcp
重生之小比特2 小时前
【算法拾光】递归、搜索与回溯算法简介
算法·深度优先