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;
    }
};
相关推荐
小O的算法实验室7 分钟前
2026年KBS,赏金猎人优化算法+多无人机移动边缘计算与路径规划,深度解析+性能实测
算法·无人机·边缘计算
用户56715047102115 分钟前
OpenClaw 记忆管理系统技术文档
算法
9359637 分钟前
练习题53-60
算法·深度优先
霖大侠1 小时前
Wavelet Meets Adam: Compressing Gradients forMemory-Efficient Training
人工智能·深度学习·算法·机器学习·transformer
小菜鸡桃蛋狗1 小时前
C++——类和对象(下)
开发语言·c++
crescent_悦1 小时前
C++:Highest Price in Supply Chain
开发语言·c++
feng_you_ying_li1 小时前
底层实现map和set的第一步,AVL树的学习
c++
AI成长日志1 小时前
【笔面试算法学习专栏】二分查找专题:力扣hot100经典题目深度解析
学习·算法·面试
lcreek1 小时前
流量优化之道:Ford-Fulkerson 最大流算法
算法·
垫脚摸太阳1 小时前
第 36 场 蓝桥·算法挑战赛·百校联赛---赛后复盘
数据结构·c++·算法