【力扣每日一题】力扣429N叉树的层序遍历

题目来源

力扣429N叉树的层序遍历

题目概述

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

思路分析

跟二叉树的层序遍历基本一致,只不过把向孩子节点列表添加左右节点该成了添加父节点的全部孩子节点。

代码实现

java实现

java 复制代码
public class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        // 结果列表
        List<List<Integer>> res = new ArrayList<>();
        // 父节点列表
        List<Node> parentList = new ArrayList<>();
        parentList.add(root);
        while (!parentList.isEmpty()) {
            // 本轮父节点转val
            List<Integer> temp = new ArrayList<>();
            // 孩子节点列表
            List<Node> sonList = new ArrayList<>();
            for (Node parent : parentList) {
                temp.add(parent.val);
                if (parent.children != null && parent.children.size() > 0) {
                    sonList.addAll(parent.children);
                }
            }
            res.add(temp);
            parentList = sonList;
        }
        return res;
    }
}

c++实现

cpp 复制代码
class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        // 结果列表
        vector<vector<int>> res;
        if (root == nullptr) {
            return res;
        }
        // 父节点列表
        vector<Node*> parent_list;
        parent_list.push_back(root);
        while (!parent_list.empty()){
            // 父节点转val
            vector<int> temp;
            // 孩子节点列表
            vector<Node*> son_list;
            for (auto parent : parent_list) {
                temp.push_back(parent->val);
                for (auto child : parent->children) {
                    son_list.push_back(child);
                }
            }
            parent_list = son_list;
            res.push_back(temp);
        }
        return res;
    }
}
相关推荐
侠客行03174 小时前
Mybatis连接池实现及池化模式
java·mybatis·源码阅读
蛇皮划水怪4 小时前
深入浅出LangChain4J
java·langchain·llm
老毛肚6 小时前
MyBatis体系结构与工作原理 上篇
java·mybatis
那个村的李富贵7 小时前
CANN加速下的AIGC“即时翻译”:AI语音克隆与实时变声实战
人工智能·算法·aigc·cann
风流倜傥唐伯虎7 小时前
Spring Boot Jar包生产级启停脚本
java·运维·spring boot
power 雀儿7 小时前
Scaled Dot-Product Attention 分数计算 C++
算法
Yvonne爱编码7 小时前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚7 小时前
JAVA进阶之路——无奖问答挑战1
java·开发语言
你这个代码我看不懂7 小时前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言
fuquxiaoguang7 小时前
深入浅出:使用MDC构建SpringBoot全链路请求追踪系统
java·spring boot·后端·调用链分析