File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments