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
- Input: root =
[1, null, 2, 3, 4, null, 5, 6]
- Expected Output:
[[1], [2, 3, 4], [5, 6]] - Justification: The root node
1is at level 0. Nodes2,3, and4are the children of1and are at level 1. Nodes5and6are the children of2, and at level 3.
Example 2
- Input: root =
[7, null, 3, 8, 5, null, 2, 9, null, 6, null, 1, 4, 10]
- Expected Output:
[[7], [3, 8, 5], [2, 9, 6, 1, 4, 10]] - Justification: The root node
7is at level 0. Nodes3,8, and5are its children at level 1. Nodes2,9,6,1,4, and10are at level 2.
Example 3
- Input: root =
[10, null, 15, 12, null, 20, null, 25, null, 30, 40]
- Expected Output:
[[10], [15, 12], [20, 25], [30, 40]] - Justification: The root node
10is at level 0. Nodes15and12are its children at level 1. Node20and25are at level 2. Nodes30, and40are 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]
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]
- Expected Output:
[[1], [2, 3, 4], [5, 6]] - Justification: The root node
1is at level 0. Nodes2,3, and4are the children of1and are at level 1. Nodes5and6are the children of2, and at level 3.
Example 2
- Input: root =
[7, null, 3, 8, 5, null, 2, 9, null, 6, null, 1, 4, 10]
- Expected Output:
[[7], [3, 8, 5], [2, 9, 6, 1, 4, 10]] - Justification: The root node
7is at level 0. Nodes3,8, and5are its children at level 1. Nodes2,9,6,1,4, and10are at level 2.
Example 3
- Input: root =
[10, null, 15, 12, null, 20, null, 25, null, 30, 40]
- Expected Output:
[[10], [15, 12], [20, 25], [30, 40]] - Justification: The root node
10is at level 0. Nodes15and12are its children at level 1. Node20and25are at level 2. Nodes30, and40are 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
Step-by-Step Algorithm
-
Initialize Result and Queue:
- Create an empty list
resultto store the final output. - If
rootisnull, return the emptyresult. - Initialize a queue and add the
rootnode to it.
- Create an empty list
-
Level Order Traversal:
- While the queue is not empty:
- Determine the number of nodes at the current level (
size). - Create an empty list
levelfor 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.
- Remove the node from the queue and add its value to
- Add
levelto theresult.
- Determine the number of nodes at the current level (
- While the queue is not empty:
-
Return Result:
- Return the
resultcontaining all level values.
- Return the
Algorithm Walkthrough
For the input root = [1, null, 2, 3, 4, null, 5, 6]:
-
Initialize:
Start by creating an empty listresult = []to store the output and a queue initialized with the root node:queue = [1]. -
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 tolevel:level = [1]. - Enqueue its children,
2, 3, 4, into the queue:queue = [2, 3, 4]. - Add the
levellist to the result:result = [[1]].
- The size of the current level is
-
Second Level:
- The size of the current level is
size = 3(nodes2, 3, 4). - Create an empty list for this level:
level = []. - Dequeue node
2from the queue, add its value tolevel:level = [2], and enqueue its children5, 6:queue = [3, 4, 5, 6]. - Dequeue node
3, add its value tolevel:level = [2, 3](node3has no children). - Dequeue node
4, add its value tolevel:level = [2, 3, 4](node4has no children). - Add the
levellist to the result:result = [[1], [2, 3, 4]].
- The size of the current level is
-
Third Level:
- The size of the current level is
size = 2(nodes5, 6). - Create an empty list for this level:
level = []. - Dequeue node
5from the queue, add its value tolevel:level = [5](node5has no children). - Dequeue node
6, add its value tolevel:level = [5, 6](node6has no children). - Add the
levellist to the result:result = [[1], [2, 3, 4], [5, 6]].
- The size of the current level is
-
Completion:
- The queue is now empty, which means all levels have been processed.
- Return the
result:[[1], [2, 3, 4], [5, 6]].
Code
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 Nis 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.
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.
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.
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.
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.