-
Notifications
You must be signed in to change notification settings - Fork 0
/
589-n-ary-tree-preorder-traversal.cpp
52 lines (43 loc) · 1.3 KB
/
589-n-ary-tree-preorder-traversal.cpp
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Title: N-ary Tree Preorder Traversal
// Description:
// 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)
// Link: https://leetcode.com/problems/n-ary-tree-preorder-traversal/
// Time complexity: O(n)
// Space complexity: O(n)
/*
// 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:
// iterative DFS (Depth First Search)
std::vector<int> preorder(Node *root) {
std::stack<Node *> processingStack; {
if (root != NULL) processingStack.push(root);
}
std::vector<int> result;
while (!processingStack.empty()) {
Node *node = processingStack.top(); processingStack.pop();
result.push_back(node->val);
for (auto it = node->children.rbegin(); it != node->children.rend(); ++it) {
Node *child = *it;
processingStack.push(child);
}
}
return result;
}
};