Skip to content

Commit bdc70c6

Browse files
authored
Merge pull request #2066 from andrewmustea/add_0589-n-ary-tree-preorder-traversal.c
create 0589-n-ary-tree-preorder-traversal.c
2 parents f55737f + fb281bd commit bdc70c6

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Diff for: c/0589-n-ary-tree-preorder-traversal.c

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Given the root of an n-ary tree, return the preorder traversal of its nodes'
3+
* values.
4+
*
5+
* Nary-Tree input serialization is represented in their level order traversal.
6+
* Each group of children is separated by the null value (See examples)
7+
*
8+
* Constraints:
9+
*
10+
* The number of nodes in the tree is in the range [0, 104].
11+
* 0 <= Node.val <= 10^4
12+
* The height of the n-ary tree is less than or equal to 1000.
13+
*
14+
* Definition for a Node.
15+
* struct Node {
16+
* int val;
17+
* int numChildren;
18+
* struct Node** children;
19+
* };
20+
*
21+
* Note: The returned array must be malloced, assume caller calls free().
22+
*
23+
* Space: O(n)
24+
* Time: O(n)
25+
*/
26+
27+
void traverse(struct Node* root, int *ret, int* index) {
28+
if (!root)
29+
return;
30+
31+
ret[(*index)++] = root->val;
32+
33+
for (int i = 0; i < root->numChildren; ++i)
34+
traverse(root->children[i], ret, index);
35+
}
36+
37+
int* preorder(struct Node* root, int* returnSize) {
38+
int *ret = malloc(10000 * sizeof(int));
39+
*returnSize = 0;
40+
traverse(root, ret, returnSize);
41+
return ret;
42+
}

0 commit comments

Comments
 (0)