Knowledge Guide
HomeDSATrees

hard N-ary Tree Level Order Traversal

Problem Statement

Given an n-ary tree, return a list representing the level order traversal of the nodes' values in this tree.

The input tree is serialized in an array format using level order traversal, where the children of each node are grouped together and separated by a null value.

Examples

Example 1

Image
Image

Example 2

Image
Image

Example 3

Image
Image

Constraints:

Try it yourself

Try solving this question here:

✅ Solution N-ary Tree Level Order Traversal

Problem Statement

Given an n-ary tree, return a list representing the level order traversal of the nodes' values in this tree.

The input tree is serialized in an array format using level order traversal, where the children of each node are grouped together and separated by a null value.

Examples

Example 1

  • Input: root = [1, null, 2, 3, 4, null, 5, 6]
Image
Image
  • Expected Output: [[1], [2, 3, 4], [5, 6]]
  • Justification: The root node 1 is at level 0. Nodes 2, 3, and 4 are the children of 1 and are at level 1. Nodes 5 and 6 are the children of 2, and at level 3.

Example 2

  • Input: root = [7, null, 3, 8, 5, null, 2, 9, null, 6, null, 1, 4, 10]
Image
Image
  • Expected Output: [[7], [3, 8, 5], [2, 9, 6, 1, 4, 10]]
  • Justification: The root node 7 is at level 0. Nodes 3, 8, and 5 are its children at level 1. Nodes 2, 9, 6, 1, 4, and 10 are at level 2.

Example 3

  • Input: root = [10, null, 15, 12, null, 20, null, 25, null, 30, 40]
Image
Image
  • Expected Output: [[10], [15, 12], [20, 25], [30, 40]]
  • Justification: The root node 10 is at level 0. Nodes 15 and 12 are its children at level 1. Node 20 and 25 are at level 2. Nodes 30, and 40 are at level 3.

Constraints:

  • The height of the n-ary tree is less than or equal to 1000
  • The total number of nodes is between [0, 104]

Solution

To solve this problem, we use a queue-based approach to perform a level order traversal of the n-ary tree. The main idea is to process all nodes level by level, starting from the root. We use a queue to keep track of nodes at each level. At each step, we remove nodes from the queue, record their values, and add their children to the queue. This ensures that we traverse all nodes at the current level before moving to the next.

This approach is effective because it processes each node exactly once, which makes it efficient with a time complexity of , where N is the total number of nodes in the tree. The use of a queue helps manage nodes level by level, ensuring that the output is correctly grouped. By storing nodes of each level in a separate list, we maintain the order of traversal and construct the desired output format.

Step-by-Step Algorithm

  1. Initialize Result and Queue:

    • Create an empty list result to store the final output.
    • If root is null, return the empty result.
    • Initialize a queue and add the root node to it.
  2. Level Order Traversal:

    • While the queue is not empty:
      • Determine the number of nodes at the current level (size).
      • Create an empty list level for the current level values.
      • For each node at the current level:
        • Remove the node from the queue and add its value to level.
        • Add all children of the node to the queue.
      • Add level to the result.
  3. Return Result:

    • Return the result containing all level values.

Algorithm Walkthrough

For the input root = [1, null, 2, 3, 4, null, 5, 6]:

  1. Initialize:
    Start by creating an empty list result = [] to store the output and a queue initialized with the root node: queue = [1].

  2. First Level:

    • The size of the current level is size = 1 (only the root node).
    • Create an empty list for this level: level = [].
    • Dequeue the first node, 1, from the queue, and add its value to level: level = [1].
    • Enqueue its children, 2, 3, 4, into the queue: queue = [2, 3, 4].
    • Add the level list to the result: result = [[1]].
  3. Second Level:

    • The size of the current level is size = 3 (nodes 2, 3, 4).
    • Create an empty list for this level: level = [].
    • Dequeue node 2 from the queue, add its value to level: level = [2], and enqueue its children 5, 6: queue = [3, 4, 5, 6].
    • Dequeue node 3, add its value to level: level = [2, 3] (node 3 has no children).
    • Dequeue node 4, add its value to level: level = [2, 3, 4] (node 4 has no children).
    • Add the level list to the result: result = [[1], [2, 3, 4]].
  4. Third Level:

    • The size of the current level is size = 2 (nodes 5, 6).
    • Create an empty list for this level: level = [].
    • Dequeue node 5 from the queue, add its value to level: level = [5] (node 5 has no children).
    • Dequeue node 6, add its value to level: level = [5, 6] (node 6 has no children).
    • Add the level list to the result: result = [[1], [2, 3, 4], [5, 6]].
  5. Completion:

    • The queue is now empty, which means all levels have been processed.
    • Return the result: [[1], [2, 3, 4], [5, 6]].

Code

java
import java.util.*;

// Definition for a NAryNode.
// class NAryNode {
//     public int val; // Value of the node
//     public List<NAryNode> children; // List to store children of the current node

//     // Default constructor
//     public NAryNode() {
//         children = new ArrayList<>(); // Initialize the children list
//     }

//     // Constructor with value
//     public NAryNode(int _val) {
//         val = _val;
//         children = new ArrayList<>(); // Initialize the children list
//     }

//     // Constructor with value and children
//     public NAryNode(int _val, List<NAryNode> _children) {
//         val = _val;
//         children = _children; // Assign provided children list
//     }
// }

class Solution {

  public List<List<Integer>> levelOrder(NAryNode root) {
    List<List<Integer>> result = new ArrayList<>(); // Result list to store levels
    if (root == null) return result; // Return empty result if root is null

    Queue<NAryNode> queue = new LinkedList<>(); // Queue to perform level order traversal
    queue.offer(root); // Start with the root node

    while (!queue.isEmpty()) {
      int size = queue.size(); // Number of nodes at the current level
      List<Integer> level = new ArrayList<>(); // List to store current level nodes

      for (int i = 0; i < size; i++) {
        NAryNode node = queue.poll(); // Dequeue the front node
        level.add(node.val); // Add node value to the current level
        for (NAryNode child : node.children) {
          queue.offer(child); // Enqueue all children of the current node
        }
      }
      result.add(level); // Add the current level to the result
    }
    return result; // Return the level order traversal
  }

  public static void main(String[] args) {
    // Create test cases using the provided examples
    NAryNode root1 = new NAryNode(7); // Root node with value 7
    NAryNode node3 = new NAryNode(3); // Node with value 3
    NAryNode node8 = new NAryNode(8); // Node with value 8
    NAryNode node5 = new NAryNode(5); // Node with value 5
    NAryNode node2 = new NAryNode(2); // Node with value 2
    NAryNode node9 = new NAryNode(9); // Node with value 9
    NAryNode node6 = new NAryNode(6); // Node with value 6
    NAryNode node1 = new NAryNode(1); // Node with value 1
    NAryNode node4 = new NAryNode(4); // Node with value 4
    NAryNode node10 = new NAryNode(10); // Node with value 10

    // Build the tree structure
    root1.children.add(node3);
    root1.children.add(node8);
    root1.children.add(node5);

    node3.children.add(node2);
    node3.children.add(node9);

    node8.children.add(node6);

    node5.children.add(node1);
    node5.children.add(node4);
    node5.children.add(node10);

    Solution solution = new Solution();
    System.out.println(solution.levelOrder(root1)); // Expected output: [[7], [3, 8, 5], [2, 9, 6, 1, 4, 10]]
  }
}

Complexity Analysis

Time Complexity

  • The algorithm traverses each node in the n-ary tree exactly once.
  • For each node, the algorithm processes its children, which involves adding them to the queue.
  • Thus, the total time complexity is , where N is the total number of nodes in the tree.

Space Complexity

  • The queue may store up to nodes at the widest level of the tree, where W is the maximum width of the tree.
  • Therefore, the space complexity is in the worst case, which occurs when the tree is a balanced tree or has a large number of nodes at the same level.
🤖 Don't fully get this? Learn it with Claude

Stuck on N-ary Tree Level Order Traversal? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **N-ary Tree Level Order Traversal** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **N-ary Tree Level Order Traversal** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **N-ary Tree Level Order Traversal**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **N-ary Tree Level Order Traversal**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes