Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitbdc70c6

Browse files
authored
Merge pull requestneetcode-gh#2066 from andrewmustea/add_0589-n-ary-tree-preorder-traversal.c
create 0589-n-ary-tree-preorder-traversal.c
2 parentsf55737f +fb281bd commitbdc70c6

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
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+
voidtraverse(structNode*root,int*ret,int*index) {
28+
if (!root)
29+
return;
30+
31+
ret[(*index)++]=root->val;
32+
33+
for (inti=0;i<root->numChildren;++i)
34+
traverse(root->children[i],ret,index);
35+
}
36+
37+
int*preorder(structNode*root,int*returnSize) {
38+
int*ret=malloc(10000*sizeof(int));
39+
*returnSize=0;
40+
traverse(root,ret,returnSize);
41+
returnret;
42+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp