LeetCode每日一题589. N-ary Tree Preorder Traversal

文章目录

一、题目

Given the root of an n-ary tree, return the preorder traversal of its nodes' values.

Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)

Example 1:

Input: root = 1,null,3,2,4,null,5,6

Output: 1,3,5,6,2,4

Example 2:

Input: 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

Output: 1,2,3,6,7,11,14,4,8,12,5,9,13,10

Constraints:

The number of nodes in the tree is in the range 0, 104.

0 <= Node.val <= 104

The height of the n-ary tree is less than or equal to 1000.

Follow up: Recursive solution is trivial, could you do it iteratively?

二、题解

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

    Node() {}

    Node(int _val) {
        val = _val;
    }

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

class Solution {
public:
    vector<int> res;
    void npreorder(Node* root){
        if(!root) return;
        res.push_back(root->val);
        for(int i = 0;i < root->children.size();i++){
            npreorder(root->children[i]);
        }
    }
    vector<int> preorder(Node* root) {
        npreorder(root);
        return res;
    }
};
相关推荐
欧特克_Glodon2 小时前
OpenCV计算机视觉开发入门与实践<二十七>:图像分割概述
c++·人工智能·opencv·计算机视觉
蒸蒸yyyyzwd2 小时前
cpp 选手秋招学习笔记 day21
c++·面试·八股
alphaTao2 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
Interview Aid1123 小时前
TikTok OA 四题分享|半小时内 AC,题目基本都是实现题
java·开发语言·算法·面试·职场和发展
顶点多余12 小时前
那些在算法中适合巩固的知识点---1
java·前端·算法
AI情绪识别开源12 小时前
检信 ALLEMOTION OS 加密打包可执行程序 — 全面测试报告版本: v1.3功能测试 / 性能测试 /
开发语言·数据结构·人工智能·功能测试
罗西的思考13 小时前
【Agentic RL / 强化学习框架】Molt 设计解读
人工智能·算法·机器学习
「QT(C++)开发工程师」13 小时前
C++ auto 用法详解
开发语言·c++
OPEN-F14 小时前
C++STL教程:容器适配器与实用工具
开发语言·c++
OPEN-F14 小时前
C++模板教程:变参模板、折叠表达式与SFINAE
java·开发语言·c++