0%

n-ary-tree-postorder-traversal

N-ary Tree Postorder Traversal – LeetCode 590

Problem

Description

Given an n-ary tree, return the postorder 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){
for(auto &i : root->children)
recursive(i);
ans.emplace_back(root->val);
}
}
public:
vector<int> postorder(Node* root) {
recursive(root);
return ans;
}
};

思路

简单的便利。时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$48$ ms,排名$56.84\%$

Better

思路

还没看到更好的思路