VOOZH about

URL: https://www.geeksforgeeks.org/dsa/level-order-traversal-of-n-ary-tree/

⇱ Level Order Traversal of N-ary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Level Order Traversal of N-ary Tree

Last Updated : 23 Jul, 2025

Given an N-ary Tree. The task is to print the level order traversal of the tree where each level will be in a new line.

Examples:

Input:

👁 Image
Image

Output: 
1
3 2 4
5 6
Explanation: At level 1: only 1 is present.
At level 2: 3, 2, 4 is present
At level 3: 5, 6 is present

Input:

👁 Image
Image

Output:  
1
2 3 4 5
6 7 8 9 10
11 12 13
14
Explanation: For the above example there are 5 level present in the n-ary tree.
At level 1: only 1 is present.
At level 2: 2, 3, 4, 5 is present.
At level 3: 6, 7, 8, 9, 10 is present
At level 4:11, 12, 13 is present
At level 5 :- 14 is present

Approach 1: Using BFS 

The approach of the problem is to use Level Order Traversal and store all the levels in a 2D array where each of the levels is stored in a different row.

Follow the below steps to implement the approach:

  • Create a vector ans and temp to store the level order traversal of the N-ary tree.
  • Push the root node in the queue.
  • Run a while loop until the queue is not empty:
    • Determine the size of the current level which is the size of the queue (say N):
      • Run a loop for i = 1 to N
      • In each step delete the front node (say cur) and push its data to the temp as a part of the current level.
      • Push all the children of cur into the queue.
    • Push the temp into the final ans vector which stores the different levels in different rows.
  • Return the ans vector.

Below is the implementation of the above approach:


Output
1 
3 2 4 
5 6 

Time Complexity: O(V) where V is the number of nodes
Auxiliary Space: O(V)

Approach 2: Using DFS 

The approach of the problem is to use Level Order Traversal using DFS and store all the levels in a 2D array where each of the levels is stored in a different row.

  • LevelOrder function will update ans with the current value, pushing it in with a new sub-vector if one matching the level is not present already into ans.
  • Function will increase level by 1;
  • It will call itself recursively on all the children;
  • It will backtrack level.

Below is the implementation of the above approach:


Output
1 
3 2 4 
5 6 

Time Complexity: O(V)
Auxiliary Space: O(V)

Comment