0%

n-ary-tree-preorder-traversal

N-ary Tree Preorder Traversal – LeetCode 589

Problem

Description

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

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;

Node() {}

Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
private:
vector<int> ans;

void recursive(Node *root){
if(root){
ans.emplace_back(root->val);
for(auto &i : root->children)
recursive(i);
}
}
public:
vector<int> preorder(Node* root) {
recursive(root);
return ans;
}
};

思路

简单的遍历。时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$44$ ms,排名$1.34\%$

Better

思路

还没看到更好的思路。