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 vectorans and temp to store the level order traversal of the N-ary tree.
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: