429. N 叉树的层序遍历

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

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

示例 1:

复制代码
输入:root = [1,null,3,2,4,null,5,6]
输出:[[1],[3,2,4],[5,6]]

示例 2:

复制代码
输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]

提示:

  • 树的高度不会超过 1000
  • 树的节点总数在 [0, 10^4] 之间

题解:

直接进行遍历,用临时变量保存所有下一层节点。

code:

java 复制代码
/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
        public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        boolean isContinue = true;
        List<Node> tmp = new ArrayList<Node>();
        List<Node> tmp2 = new ArrayList<Node>();
        tmp.add(root);
        while(isContinue) {
            List<Integer> list = new ArrayList<Integer>();
            for(Node node : tmp) {
                if (node == null) {
                    continue;
                }
                list.add(node.val);
                tmp2.addAll(node.children);
            }
            result.add(list);
            if (tmp2.isEmpty()) {
                isContinue = false;
            }
            tmp = tmp2;
            tmp2 = new ArrayList<Node>();
        }
        
        return result;
    }
}

使用队列实现

java 复制代码
public List<List<Integer>> levelOrder(Node root) {
        if (root == null) {
            return new ArrayList<List<Integer>>();
        }

        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        Queue<Node> queue = new ArrayDeque<Node>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int cnt = queue.size();
            List<Integer> level = new ArrayList<Integer>();
            for (int i = 0; i < cnt; ++i) {
                Node cur = queue.poll();
                level.add(cur.val);
                for (Node child : cur.children) {
                    queue.offer(child);
                }
            }
            ans.add(level);
        }

        return ans;
    
}
相关推荐
曹牧21 分钟前
Java:Java 数组转 List
java·开发语言·windows
Keven_1133 分钟前
算法札记:ACM中将高精度算法融于题目的模板
算法·acm·精度
小七在进步35 分钟前
数据结构:快速排序
数据结构·算法·排序算法
下辈子不要当码农37 分钟前
Day7-Linux软件编程(进程与线程(3))
java·开发语言
闻缺陷则喜何志丹38 分钟前
【计算几何 第十一章】凸包:混合物
数学·算法·计算几何·凸包·混合物·凸组合
土司大王39 分钟前
LeetCode hot100——二叉树的最大深度
算法·leetcode·职场和发展
高亦真1 小时前
今天是学习嵌入式的第31天
linux·学习·算法
深入云栈1 小时前
一文搞懂Netty 4.2六大核心概念:Channel/EventLoop/Selector/ByteBuf 如何关联
java·后端
hh9501 小时前
Agent Plan × DeepSeek Harness:角色 Prompt 驱动的 Agent 分工优化与协作质量实验
java·前端·人工智能·prompt·adg·agent plan·adg成都社区
MetaLite1 小时前
SpringBoot接口通用返回对象Resp设计
java·spring boot·后端