Problem
Given 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).
Examples
Example 1:
graph TD 1 --- A[3] & B[2] & C[4] A --- 5 & 6
(have to use A, B, C in mermaid to make the ordering of nodes better)
|
|
Example 2:
graph TD 1 --- 2 & 3 & 4 & 5 3 --- 6 & 7 7 --- 11 11 --- 14 4 --- 8 8 --- 12 5 --- 9 & 10 9 --- 13
|
|
Solution
Method 1 - BFS
The goal is to perform a level-order traversal on an n-ary tree, which is essentially visiting the nodes level by level. The challenge arises because the tree is n-ary, meaning each node can have multiple children, unlike a binary tree with only two children.
The breadth-first search (BFS) approach is ideal for this problem as it inherently processes nodes level by level. Here’s the step-by-step approach:
- Use a queue to traverse nodes level by level.
- Start with the root node in the queue.
- For each level, process all nodes in the queue, collect their values, and enqueue their children.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the total number of nodes. Each node is visited once during traversal. - 🧺 Space complexity:
O(n)
, for storing nodes in the queue.