Skip to content

Commit 586b7de

Browse files
authored
Create n-ary-tree-postorder-traversal.cpp
1 parent d9d12fe commit 586b7de

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
/*
5+
// Definition for a Node.
6+
class Node {
7+
public:
8+
int val;
9+
vector<Node*> children;
10+
11+
Node() {}
12+
13+
Node(int _val, vector<Node*> _children) {
14+
val = _val;
15+
children = _children;
16+
}
17+
};
18+
*/
19+
class Solution {
20+
public:
21+
vector<int> postorder(Node* root) {
22+
if (!root) {
23+
return {};
24+
}
25+
vector<int> result;
26+
vector<Node*> stack{root};
27+
while (!stack.empty()) {
28+
auto node = stack.back(); stack.pop_back();
29+
result.emplace_back(node->val);
30+
for (const auto& child : node->children) {
31+
if (child) {
32+
stack.emplace_back(child);
33+
}
34+
}
35+
}
36+
reverse(result.begin(), result.end());
37+
return result;
38+
}
39+
};

0 commit comments

Comments
 (0)