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)
Example 1:

Input: root = [1,null,3,2,4,null,5,6] Output: [1,3,5,6,2,4]
Example 2:

Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
Constraints:
[0, 104].0 <= Node.val <= 1041000.
Follow up: Recursive solution is trivial, could you do it iteratively?
This approach leverages the simplicity of recursion to perform a preorder traversal on an n-ary tree. We start at the root node, then recursively process each child's subtree.
The C code defines a node structured to represent each tree node with value and children. Using a helper function, preorderHelper, it ensures the tree is traversed in preorder by accessing each node's value before recursively calling the helper on each child.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the number of nodes in the tree, since we visit each node once.
Space Complexity: O(n) for the recursion stack used in the helper function.
This approach uses an explicit stack to simulate the call stack of recursion. We manually manage traversals seen in recursion, starting from the root node, iteratively processing each node, then adding each child to a stack for future visits.
This C solution uses a stack structure to handle the iterative traversal. The stack manually manages nodes left to process, with each node added to the result upon visitation. It handles children in reverse order to maintain correct preorder evaluation.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n). Space Complexity: O(n), as most nodes can be stored in the stack in the worst case.
| Approach | Complexity |
|---|---|
| Recursive Approach | Time Complexity: O(n), where n is the number of nodes in the tree, since we visit each node once. |
| Iterative Approach with Stack | Time Complexity: O(n). Space Complexity: O(n), as most nodes can be stored in the stack in the worst case. |
Serialize and Deserialize Binary Tree - Preorder Traversal - Leetcode 297 - Python • NeetCode • 128,074 views views
Watch 9 more video solutions →Practice N-ary Tree Preorder Traversal with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor