Problem
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)
Examples
Example 1:
graph TD 1 --- A[3] & B[2] & C[4] A --- 5 & 6
(have to use A, B, C in mermaid to make the ordering of nodes better)
|
|
Example 2:
graph TD 1 --- 2 & 3 & 4 & 5 3 --- 6 & 7 7 --- 11 11 --- 14 4 --- 8 8 --- 12 5 --- 9 & 10 9 --- 13
|
|
Solution
Method 1 - DFS
Code
|
|
Complexity
- Time:
O(N)
- where N is number of nodes - Space:
O(1)