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
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
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:
C++
// C++ code for above implementation#include<bits/stdc++.h>usingnamespacestd;structNode{charval;vector<Node*>children;};// Utility function to create a new tree nodeNode*newNode(intkey){Node*temp=newNode;temp->val=key;returntemp;}// Function for level order traversal for n-array treevector<vector<int>>levelOrder(Node*root){vector<vector<int>>ans;if(!root)cout<<"N-Ary tree does not any nodes";// Create a queue namely main_queuequeue<Node*>main_queue;// Push the root value in the main_queuemain_queue.push(root);// Create a temp vector to store the all the node values// present at a particular levelvector<int>temp;// Run a while loop until the main_queue is emptywhile(!main_queue.empty()){// Get the front of the main_queueintn=main_queue.size();// Iterate through the current levelfor(inti=0;i<n;i++){Node*cur=main_queue.front();main_queue.pop();temp.push_back(cur->val);for(autou:cur->children)main_queue.push(u);}ans.push_back(temp);temp.clear();}returnans;}// Driver codeintmain(){Node*root=newNode(1);root->children.push_back(newNode(3));root->children.push_back(newNode(2));root->children.push_back(newNode(4));root->children[0]->children.push_back(newNode(5));root->children[0]->children.push_back(newNode(6));// LevelOrderTraversal obj;vector<vector<int>>ans=levelOrder(root);for(autov:ans){for(intx:v)cout<<x<<" ";cout<<endl;}return0;}// This code is contributed by Aditya Kumar (adityakumar129)
Java
importjava.util.*;publicclassMain{staticclassNode{publicintval;publicVector<Node>children;publicNode(intkey){val=key;children=newVector<Node>();}}// Utility function to create a new tree nodestaticNodenewNode(intkey){Nodetemp=newNode(key);returntemp;}// Function for level order traversal for n-array treestaticList<List<Integer>>levelOrder(Noderoot){List<List<Integer>>ans=newArrayList<>();if(root==null)System.out.println("N-Ary tree does not any nodes");// Create one queue main_queueQueue<Node>main_queue=newLinkedList<>();// Push the root value in the main_queuemain_queue.offer(root);// Traverse the N-ary Tree by levelwhile(!main_queue.isEmpty()){// Create a temp vector to store the all the// node values present at a particular levelList<Integer>temp=newArrayList<>();intsize=main_queue.size();// Iterate through the current levelfor(inti=0;i<size;i++){Nodenode=main_queue.poll();temp.add(node.val);for(Nodechild:node.children){main_queue.offer(child);}}ans.add(temp);}returnans;}// Utility function to print the level order traversalpublicstaticvoidprintList(List<List<Integer>>temp){for(List<Integer>it:temp){for(Integeret:it)System.out.print(et+" ");System.out.println();}}publicstaticvoidmain(String[]args){Noderoot=newNode(1);(root.children).add(newNode(3));(root.children).add(newNode(2));(root.children).add(newNode(4));(root.children.get(0).children).add(newNode(5));(root.children.get(0).children).add(newNode(6));List<List<Integer>>ans=levelOrder(root);printList(ans);}}// This code is contributed by Sania Kumari Gupta
Python3
# Python code for above implementationclassNode:def__init__(self,key):self.key=keyself.child=[]# Utility function to create a new tree nodedefnewNode(key):temp=Node(key)returntemp# Prints the n-ary tree level wisedefLevelOrderTraversal(root):if(root==None):return;# Standard level order traversal code# using queueq=[]# Create a queueq.append(root);# Enqueue rootwhile(len(q)!=0):n=len(q);# If this node has childrenwhile(n>0):# Dequeue an item from queue and print itp=q[0]q.pop(0);print(p.key,end=' ')# Enqueue all children of the dequeued itemforiinrange(len(p.child)):q.append(p.child[i]);n-=1print()# Print new line between two levelsif__name__=='__main__':root=newNode(1);root.child.append(newNode(3));root.child.append(newNode(2));root.child.append(newNode(4));root.child[0].child.append(newNode(5));root.child[0].child.append(newNode(6));# LevelOrderTraversal obj;LevelOrderTraversal(root);# This code is contributed by poojaagarwal2.
C#
// C# code implementation for the abvoe approachusingSystem;usingSystem.Collections.Generic;usingSystem.Linq;publicclassNode{publicintval;publicList<Node>children;publicNode(intkey){val=key;children=newList<Node>();}}publicclassGFG{// Utility function to create a new tree nodestaticNodenewNode(intkey){Nodetemp=newNode(key);returntemp;}// Function for level order traversal for n-array treestaticList<List<int>>levelOrder(Noderoot){List<List<int>>ans=newList<List<int>>();if(root==null)Console.WriteLine("N-Ary tree does not any nodes");// Create one queue main_queueQueue<Node>main_queue=newQueue<Node>();// Push the root value in the main_queuemain_queue.Enqueue(root);// Traverse the N-ary Tree by levelwhile(main_queue.Any()){// Create a temp vector to store the all the// node values present at a particular levelList<int>temp=newList<int>();intsize=main_queue.Count;// Iterate through the current levelfor(inti=0;i<size;i++){Nodenode=main_queue.Dequeue();temp.Add(node.val);foreach(Nodechildinnode.children){main_queue.Enqueue(child);}}ans.Add(temp);}returnans;}// Utility function to print the level order traversalpublicstaticvoidprintList(List<List<int>>temp){foreach(List<int>itintemp){foreach(intetinit)Console.Write(et+" ");Console.WriteLine();}}staticpublicvoidMain(){// CodeNoderoot=newNode(1);(root.children).Add(newNode(3));(root.children).Add(newNode(2));(root.children).Add(newNode(4));(root.children[0].children).Add(newNode(5));(root.children[0].children).Add(newNode(6));List<List<int>>ans=levelOrder(root);printList(ans);}}// This code is contributed by karthik.
JavaScript
// Javascript code for above implementationclassNode{constructor(val){this.val=val;this.children=newArray();}}// Function for level order traversal for n-array treefunctionlevelOrder(root){letans=[];if(!root)console.log("N-Ary tree does not any nodes");// Create a queue namely main_queueletmain_queue=[];// Push the root value in the main_queuemain_queue.push(root);// Create a temp vector to store the all the node values// present at a particular levellettemp=[];// Run a while loop until the main_queue is emptywhile(main_queue.length){// Get the front of the main_queueletn=main_queue.length;// Iterate through the current levelfor(leti=0;i<n;i++){letcur=main_queue.shift();temp.push(cur.val);for(letuofcur.children)main_queue.push(u);}ans.push(temp);temp=[];}returnans;}// Driver codeletroot=newNode(1);root.children.push(newNode(3));root.children.push(newNode(2));root.children.push(newNode(4));root.children[0].children.push(newNode(5));root.children[0].children.push(newNode(6));// LevelOrderTraversal obj;letans=levelOrder(root);for(letvofans){for(letxofv)console.log(x+" ");console.log("<br>");}
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:
C++
// C++ code for above implementation#include<bits/stdc++.h>usingnamespacestd;vector<vector<int>>ans;intlevel=0;structNode{charval;vector<Node*>children;};Node*newNode(intkey){Node*temp=newNode;temp->val=key;returntemp;}voidlevelOrder(Node*root){if(ans.size()==level)ans.push_back({root->val});elseans[level].push_back(root->val);level++;for(Node*n:root->children)levelOrder(n);level--;}intmain(){Node*root=newNode(1);root->children.push_back(newNode(3));root->children.push_back(newNode(2));root->children.push_back(newNode(4));root->children[0]->children.push_back(newNode(5));root->children[0]->children.push_back(newNode(6));// LevelOrderTraversal obj;levelOrder(root);for(autov:ans){for(intx:v)cout<<x<<" ";cout<<endl;}return0;}
Java
/*package whatever //do not write package name here */importjava.io.*;importjava.util.*;publicclassGFG{staticList<List<Integer>>result=newArrayList<>();staticintlevel=0;staticclassNode{publicintval;publicVector<Node>children;publicNode(intkey){val=key;children=newVector<Node>();}}// Utility function to create a new tree nodestaticNodenewNode(intkey){Nodetemp=newNode(key);returntemp;}// method to find level order traversal of n-ary treestaticvoidlevelOrder(Nodenode){if(node==null){return;}List<Integer>list=result.size()>level?result.get(level):newArrayList<>();// adding node value to the listlist.add(node.val);if(result.size()<=level){result.add(list);}// promoting/incrementing the level to nextlevel++;for(Noden:node.children){levelOrder(n);}level--;}// utility function to print level order traversalpublicstaticvoidprintList(List<List<Integer>>temp){for(List<Integer>it:temp){for(Integeret:it)System.out.print(et+" ");System.out.println();}}publicstaticvoidmain(String[]args){Noderoot=newNode(1);(root.children).add(newNode(3));(root.children).add(newNode(2));(root.children).add(newNode(4));(root.children.get(0).children).add(newNode(5));(root.children.get(0).children).add(newNode(6));levelOrder(root);printList(result);}}
Python3
# Python code for above implementationans=[]level=0classNode:def__init__(self,val):self.val=valself.children=[]deflevelOrder(root):globalleveliflen(ans)==level:ans.append([root.val])else:ans[level].append(root.val)level+=1forninroot.children:levelOrder(n)level-=1root=Node(1)root.children.append(Node(3))root.children.append(Node(2))root.children.append(Node(4))root.children[0].children.append(Node(5))root.children[0].children.append(Node(6))levelOrder(root)forvinans:forxinv:print(x,end=" ")print()# This code is contributed by Tapesh(tapeshdua420)
C#
// C# code for the above approachusingSystem;usingSystem.Collections.Generic;publicclassGFG{staticList<List<int>>result=newList<List<int>>();staticintlevel=0;publicclassNode{publicintval;publicList<Node>children;publicNode(intkey){val=key;children=newList<Node>();}}// Utility function to create a new tree nodestaticNodenewNode(intkey){Nodetemp=newNode(key);returntemp;}// method to find level order traversal of n-ary treestaticvoidlevelOrder(Nodenode){if(node==null){return;}List<int>list=result.Count>level?result[level]:newList<int>();// adding node value to the listlist.Add(node.val);if(result.Count<=level){result.Add(list);}// promoting/incrementing the level to nextlevel++;foreach(Nodeninnode.children){levelOrder(n);}level--;}// utility function to print level order traversalpublicstaticvoidprintList(List<List<int>>temp){foreach(List<int>itintemp){foreach(intetinit){Console.Write(et+" ");}Console.WriteLine();}}staticpublicvoidMain(){// CodeNoderoot=newNode(1);(root.children).Add(newNode(3));(root.children).Add(newNode(2));(root.children).Add(newNode(4));(root.children[0].children).Add(newNode(5));(root.children[0].children).Add(newNode(6));levelOrder(root);printList(result);}}// This code is contributed by sankar.
JavaScript
// JavaScript code for the above approachconstans=[];letlevel=0;classNode{constructor(val){this.val=val;this.children=[];}}functionlevelOrder(root){if(ans.length===level)ans.push([root.val]);elseans[level].push(root.val);level++;for(constnofroot.children)levelOrder(n);level--;}// create treeconstroot=newNode(1);root.children.push(newNode(3));root.children.push(newNode(2));root.children.push(newNode(4));root.children[0].children.push(newNode(5));root.children[0].children.push(newNode(6));levelOrder(root);for(constvofans){for(constxofv){console.log(x+" ");}console.log('<br>');}// This code is contributed by Potta Lokesh