Given a generic tree, perform a Level order traversal and print all of its nodes
Examples:
Input : 10
/ / \ \
2 34 56 100
/ \ | / | \
77 88 1 7 8 9
Output : 10
2 34 56 100
77 88 1 7 8 9
Input : 1
/ / \ \
2 3 4 5
/ \ | / | \
6 7 8 9 10 11
Output : 1
2 3 4 5
6 7 8 9 10 11
The approach to this problem is similar to Level Order traversal in a binary tree. We Start with pushing root node in a queue and for each node we pop it, print it and push all its child in the queue.
In case of a generic tree we store child nodes in a vector. Thus we put all elements of the vector in the queue.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int key;
vector<Node *>child;
};
Node *newNode( int key)
{
Node *temp = new Node;
temp->key = key;
return temp;
}
void LevelOrderTraversal(Node * root)
{
if (root==NULL)
return ;
queue<Node *> q;
q.push(root);
while (!q.empty())
{
int n = q.size();
while (n > 0)
{
Node * p = q.front();
q.pop();
cout << p->key << " " ;
for ( int i=0; i<p->child.size(); i++)
q.push(p->child[i]);
n--;
}
cout << endl;
}
}
int main()
{
Node *root = newNode(10);
(root->child).push_back(newNode(2));
(root->child).push_back(newNode(34));
(root->child).push_back(newNode(56));
(root->child).push_back(newNode(100));
(root->child[0]->child).push_back(newNode(77));
(root->child[0]->child).push_back(newNode(88));
(root->child[2]->child).push_back(newNode(1));
(root->child[3]->child).push_back(newNode(7));
(root->child[3]->child).push_back(newNode(8));
(root->child[3]->child).push_back(newNode(9));
cout << "Level order traversal Before Mirroring\n" ;
LevelOrderTraversal(root);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static class Node
{
int key;
Vector<Node >child = new Vector<>();
};
static Node newNode( int key)
{
Node temp = new Node();
temp.key = key;
return temp;
}
static void LevelOrderTraversal(Node root)
{
if (root == null )
return ;
Queue<Node > q = new LinkedList<>();
q.add(root);
while (!q.isEmpty())
{
int n = q.size();
while (n > 0 )
{
Node p = q.peek();
q.remove();
System.out.print(p.key + " " );
for ( int i = 0 ; i < p.child.size(); i++)
q.add(p.child.get(i));
n--;
}
System.out.println();
}
}
public static void main(String[] args)
{
Node root = newNode( 10 );
(root.child).add(newNode( 2 ));
(root.child).add(newNode( 34 ));
(root.child).add(newNode( 56 ));
(root.child).add(newNode( 100 ));
(root.child.get( 0 ).child).add(newNode( 77 ));
(root.child.get( 0 ).child).add(newNode( 88 ));
(root.child.get( 2 ).child).add(newNode( 1 ));
(root.child.get( 3 ).child).add(newNode( 7 ));
(root.child.get( 3 ).child).add(newNode( 8 ));
(root.child.get( 3 ).child).add(newNode( 9 ));
System.out.println( "Level order traversal " +
"Before Mirroring " );
LevelOrderTraversal(root);
}
}
|
Python3
class Node:
def __init__( self , key):
self .key = key
self .child = []
def newNode(key):
temp = Node(key)
return temp
def LevelOrderTraversal(root):
if (root = = None ):
return ;
q = []
q.append(root);
while ( len (q) ! = 0 ):
n = len (q);
while (n > 0 ):
p = q[ 0 ]
q.pop( 0 );
print (p.key, end = ' ' )
for i in range ( len (p.child)):
q.append(p.child[i]);
n - = 1
print ()
if __name__ = = '__main__' :
root = newNode( 10 );
(root.child).append(newNode( 2 ));
(root.child).append(newNode( 34 ));
(root.child).append(newNode( 56 ));
(root.child).append(newNode( 100 ));
(root.child[ 0 ].child).append(newNode( 77 ));
(root.child[ 0 ].child).append(newNode( 88 ));
(root.child[ 2 ].child).append(newNode( 1 ));
(root.child[ 3 ].child).append(newNode( 7 ));
(root.child[ 3 ].child).append(newNode( 8 ));
(root.child[ 3 ].child).append(newNode( 9 ));
print ( "Level order traversal Before Mirroring" )
LevelOrderTraversal(root);
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public class Node
{
public int key;
public List<Node >child = new List<Node>();
};
static Node newNode( int key)
{
Node temp = new Node();
temp.key = key;
return temp;
}
static void LevelOrderTraversal(Node root)
{
if (root == null )
return ;
Queue<Node > q = new Queue<Node >();
q.Enqueue(root);
while (q.Count != 0)
{
int n = q.Count;
while (n > 0)
{
Node p = q.Peek();
q.Dequeue();
Console.Write(p.key + " " );
for ( int i = 0; i < p.child.Count; i++)
q.Enqueue(p.child[i]);
n--;
}
Console.WriteLine();
}
}
public static void Main(String[] args)
{
Node root = newNode(10);
(root.child).Add(newNode(2));
(root.child).Add(newNode(34));
(root.child).Add(newNode(56));
(root.child).Add(newNode(100));
(root.child[0].child).Add(newNode(77));
(root.child[0].child).Add(newNode(88));
(root.child[2].child).Add(newNode(1));
(root.child[3].child).Add(newNode(7));
(root.child[3].child).Add(newNode(8));
(root.child[3].child).Add(newNode(9));
Console.WriteLine( "Level order traversal " +
"Before Mirroring " );
LevelOrderTraversal(root);
}
}
|
Javascript
<script>
class Node
{
constructor()
{
this .key = 0;
this .child = [];
}
};
function newNode(key)
{
var temp = new Node();
temp.key = key;
return temp;
}
function LevelOrderTraversal(root)
{
if (root == null )
return ;
var q = [];
q.push(root);
while (q.length != 0)
{
var n = q.length;
while (n > 0)
{
var p = q[0];
q.shift();
document.write(p.key + " " );
for ( var i = 0; i < p.child.length; i++)
q.push(p.child[i]);
n--;
}
document.write( "<br>" );
}
}
var root = newNode(10);
(root.child).push(newNode(2));
(root.child).push(newNode(34));
(root.child).push(newNode(56));
(root.child).push(newNode(100));
(root.child[0].child).push(newNode(77));
(root.child[0].child).push(newNode(88));
(root.child[2].child).push(newNode(1));
(root.child[3].child).push(newNode(7));
(root.child[3].child).push(newNode(8));
(root.child[3].child).push(newNode(9));
document.write( "Level order traversal " +
"Before Mirroring <br>" );
LevelOrderTraversal(root);
</script>
|
Output
Level order traversal Before Mirroring
10
2 34 56 100
77 88 1 7 8 9
Time Complexity: O(n) where n is the number of nodes in the n-ary tree.
Auxiliary Space: O(n)
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
14 Mar, 2023
Like Article
Save Article