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;
    }
};
相关推荐
leobertlan12 分钟前
痛苦系列 | DSP-03 跨越单位圆:Z变换与零极点分析
算法·程序员
蛋蛋的就会顺顺的21 分钟前
hot100 p0——栈,贪心算法,动态规划
java·前端·javascript·算法·leetcode·力扣
开发小能手1231 小时前
答案daanC语言
数据结构·算法
Navigator_Z3 小时前
LeetCode //C - 1291. Sequential Digits
c语言·算法·leetcode
WL学习笔记3 小时前
C & C++ 内存管理
c++·c++内存管理
pride.li4 小时前
第03章 Python 教程-基础语法:注释与变量
服务器·前端·后端·python·算法·计算机视觉
旺仔仔仔4 小时前
机器人项目实战(5):从单次抓取,到接收指令连续做事
算法
旺仔仔仔5 小时前
机器人项目实战(2):识别物体、提取点云,再到抓取姿态
算法
姜鱼问生5 小时前
密码明明一样,为什么 GPG 说“错的“?
后端·算法·架构
启观川5 小时前
数据结构与算法-第 3 章 常用算法-贪心算法
数据结构·笔记·python·算法·贪心算法