N-ary Tree Level Order Traversal - Problem
Given the root of an n-ary tree, return the level order 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).
In level order traversal, we visit all nodes at depth 0, then all nodes at depth 1, then all nodes at depth 2, and so on. Within each level, nodes can be visited in any order.
Input & Output
Example 1 — Basic N-ary Tree
$
Input:
root = [1,null,3,2,4,null,5,6]
›
Output:
[[1],[3,2,4],[5,6]]
💡 Note:
Level 0 contains root node 1. Level 1 contains its children 3, 2, 4. Level 2 contains children of node 3: nodes 5 and 6.
Example 2 — 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,4,5],[6,7,8,9,10],[11,12,13],[14]]
💡 Note:
Each level contains all nodes at that depth. The tree has 5 levels with varying numbers of nodes per level.
Example 3 — Single Node
$
Input:
root = [1]
›
Output:
[[1]]
💡 Note:
Tree with only root node results in single level containing just that node.
Constraints
- The height of the n-ary tree is less than or equal to 1000
- The total number of nodes is between [0, 104]
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
N-ary tree with nodes having 0 or more children
2
Level Processing
Group nodes by their depth level
3
Output Array
2D array with each level as a separate sub-array
Key Takeaway
🎯 Key Insight: Use BFS queue to naturally process nodes level by level, collecting each complete level before moving to the next
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code