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
N-ary Tree Level Order Traversal INPUT 1 3 2 4 5 6 Level 0 Level 1 Level 2 [1,null,3,2,4,null,5,6] Serialized N-ary Tree null separates children groups ALGORITHM - BFS 1 Initialize Queue Add root to queue [1] queue 2 Process Level 0 Dequeue 1, enqueue children [3, 2, 4] queue 3 Process Level 1 Dequeue all, add children [5, 6] queue 4 Process Level 2 Dequeue 5,6 - no children [] empty Queue empty - Done! FINAL RESULT Level-by-level output: Level 0: [1] Level 1: [3,2,4] Level 2: [5,6] OUTPUT: [[1],[3,2,4],[5,6]] OK - Complete 3 levels traversed Key Insight: BFS naturally processes nodes level by level. Track level size before processing to group nodes correctly. Time: O(n) - visit each node once. Space: O(n) for queue. Each iteration processes one complete level, adding all children for next level. TutorialsPoint - N-ary Tree Level Order Traversal | BFS Approach
Asked in
Amazon 15 Facebook 12 Microsoft 10 Google 8
125.0K Views
Medium Frequency
~15 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen