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;
    
}
相关推荐
在爪洼山玩泥巴15 分钟前
fastjson2 JSONPath 取不存在路径,为什么会抛 “not support”?
java·开发语言·jsonpath·fastjson
电科_银尘9 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
星落梦生10 小时前
SpringAOP基础笔记(7)
java·开发语言
金銀銅鐵11 小时前
带您看懂字节码指令(四):一条指令里有什么
java·jvm
最强小杰11 小时前
某 OpenAI 兼容网关上的 `kimi-k3.1-pro`:Cline、Zed 接入与 SSE 排错示例
java·服务器·网络·ai
Flynn Liang12 小时前
流量治理不是限流那么简单:I/O 密集型 Java 服务的 6 层防线
java·微服务·高并发·限流·熔断·系统稳定性·resilience4j
学长毕设12 小时前
基于SpringBoot智慧养老服务平台设计与实现-附源码
java·spring boot·后端
曹牧12 小时前
Java:“刷新雪崩”
java·开发语言
郝学胜-神的一滴12 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David12 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法