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;
    }
};
相关推荐
第二只羽毛4 分钟前
遵守robots协议的友好爬虫
大数据·爬虫·python·算法·网络爬虫
BestOrNothing_201515 分钟前
一篇搞懂 C++ 重载:函数重载 + 运算符重载,从入门到会用(含 ++、<<、== 实战)
c++·函数重载·运算符重载·operator·前置后置++·重载与重写
艾斯比的日常23 分钟前
Java 三色标记算法:并发垃圾回收的核心技术解析
java·开发语言·算法
2501_9411444232 分钟前
Python + C++ 异构微服务设计与优化
c++·python·微服务
CoovallyAIHub33 分钟前
抛弃LLM!MIT用纯视觉方法破解ARC难题,性能接近人类水平
深度学习·算法·计算机视觉
程序猿编码38 分钟前
PRINCE算法的密码生成器:原理与设计思路(C/C++代码实现)
c语言·网络·c++·算法·安全·prince
高洁011 小时前
具身智能-视觉语言导航(VLN)
深度学习·算法·aigc·transformer·知识图谱
Croa-vo1 小时前
TikTok 数据工程师三轮 VO 超详细面经:技术深挖 + 建模推导 + 压力测试全记录
javascript·数据结构·经验分享·算法·面试
蘑菇小白1 小时前
时间复杂度
数据结构·算法
czlczl200209251 小时前
算法:组合问题
算法·leetcode·职场和发展