Leetcode 429:N叉树的层次遍历

给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。

树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)。

思路:利用层次遍历的模板,直接遍历N叉树

java 复制代码
public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> result=new ArrayList<>();
        Queue<Node> queue=new LinkedList();
        if(root!=null) queue.add(root);
        while (!queue.isEmpty()){
            int size=queue.size();
            List<Integer> list=new ArrayList();
            for (int i=0;i<size;i++){
                Node node=queue.poll();
                list.add(node.val);
                if(node.children==null) continue;
                for(int j=0;j<node.children.size();j++){
                    queue.add(node.children.get(j));
                }
            }
            result.add(list);
        }
        return result;
    }
相关推荐
TTGGGFF39 分钟前
控制系统建模仿真(四):线性控制系统的数学模型
人工智能·算法
正在努力Coding1 小时前
SpringAI - 工具调用
java·spring·ai
晚风吹长发1 小时前
初步了解Linux中的命名管道及简单应用和简单日志
linux·运维·服务器·开发语言·数据结构·c++·算法
圣保罗的大教堂2 小时前
leetcode 3315. 构造最小位运算数组 II 中等
leetcode
我尽力学2 小时前
面试 总结
java·spring boot·面试
爬台阶的蚂蚁2 小时前
Spring AI Alibaba基础概念
java·spring·ai
Σίσυφος19002 小时前
Halcon中霍夫直线案例
算法
计算机学姐2 小时前
基于SpringBoot的演唱会抢票系统
java·spring boot·后端·spring·tomcat·intellij-idea·推荐算法
huohuopro2 小时前
Mybatis的七种传参方式
java·开发语言·mybatis
Lee_SmallNorth2 小时前
变态需求之【角色不同访问数据库的用户不同】
java·开发语言·数据库