Given a generic tree, perform a Level order traversal and print all of its nodes
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.
Output: 10 2 34 56 100 77 88 1 7 8 9
This article is contributed by Raghav Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Flatten Binary Tree in order of Level Order Traversal
- Insertion in n-ary tree in given order and Level order traversal
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Level Order Tree Traversal
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Zig Zag Level order traversal of a tree using single queue
- Density of Binary Tree using Level Order Traversal
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Perfect Binary Tree Specific Level Order Traversal
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Level Order Predecessor of a node in Binary Tree
- Level Order Successor of a node in Binary Tree
- Check if the given array can represent Level Order Traversal of Binary Search Tree
- Number of children of given node in n-ary Tree