![]() |
VOOZH | about |
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:
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)