VOOZH about

URL: https://www.geeksforgeeks.org/dsa/generic-tree-level-order-traversal/

⇱ General Tree (Each node can have arbitrary number of children) Level Order Traversal - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

General Tree (Each node can have arbitrary number of children) Level Order Traversal

Last Updated : 14 Mar, 2023

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:


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)

Comment