N-ary Tree Preorder Traversal - Problem
Given the root of an n-ary tree, return the preorder traversal of its nodes' values.
In preorder traversal, we visit nodes in this order:
- Visit the current node (process its value)
- Recursively visit all children from left to right
An n-ary tree is a tree where each node can have any number of children (0 to n), unlike binary trees which have at most 2 children.
Input Format: The tree is represented using level order traversal where each group of children is separated by null values.
Goal: Return a list containing all node values in preorder sequence.
Input & Output
example_1.py โ Simple N-ary Tree
$
Input:
root = [1,null,3,2,4,null,5,6]
โบ
Output:
[1,3,5,6,2,4]
๐ก Note:
Starting at root 1, we visit it first. Then we visit its children 3,2,4 in order. For node 3, we first visit 3 itself, then its children 5,6. Finally we visit nodes 2 and 4 (which have no children).
example_2.py โ Deeper Tree
$
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]
๐ก Note:
This demonstrates preorder traversal on a more complex tree with multiple levels. We always visit parent nodes before their children, going depth-first from left to right.
example_3.py โ Single Node
$
Input:
root = [1]
โบ
Output:
[1]
๐ก Note:
Edge case with just one node. The preorder traversal simply returns that single node's value.
Constraints
- The number of nodes in the tree is in the range [0, 104]
- 0 โค Node.val โค 104
- The height of the n-ary tree is less than or equal to 1000
- Follow up: Recursive solution is trivial, could you do it iteratively?
Visualization
Tap to expand
Understanding the Visualization
1
Start at Root
Begin at the root node and add its value to the result immediately
2
Visit Children Left-to-Right
Process each child recursively in order from left to right
3
Depth-First Pattern
For each child, complete its entire subtree before moving to the next sibling
4
Build Result
The final result contains all nodes in preorder: parent before children
Key Takeaway
๐ฏ Key Insight: Preorder traversal naturally follows parent-child relationships - we always process a node before exploring its descendants. Both recursive and iterative solutions are optimal with O(n) time complexity, visiting each node exactly once.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code