Skip to content

Commit 4d739f1

Browse files
Create n-ary_preorder_traversal.cpp
1 parent 237f037 commit 4d739f1

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

n-ary_preorder_traversal.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
// Definition for a Node.
3+
class Node {
4+
public:
5+
int val;
6+
vector<Node*> children;
7+
8+
Node() {}
9+
10+
Node(int _val) {
11+
val = _val;
12+
}
13+
14+
Node(int _val, vector<Node*> _children) {
15+
val = _val;
16+
children = _children;
17+
}
18+
};
19+
*/
20+
21+
class Solution {
22+
public:
23+
vector<int> result;
24+
25+
void helper(Node* root) {
26+
if(!root) return;
27+
28+
result.push_back(root->val);
29+
for(auto &n : root->children) {
30+
helper(n);
31+
}
32+
return;
33+
}
34+
vector<int> preorder(Node* root) {
35+
if(!root) return vector<int>();
36+
helper(root);
37+
return result;
38+
}
39+
};

0 commit comments

Comments
 (0)