Given a Binary Tree, print the nodes level wise, each level on a new line.
Output: 1 2 3 4 5
We have discussed one solution in below article.
Print level order traversal line by line | Set 1
In this post, a different approach using two queues is discussed. We can insert the first level in first queue and print it and while popping from the first queue insert its left and right nodes into the second queue. Now start printing the second queue and before popping insert its left and right child nodes into the first queue. Continue this process till both the queues become empty.
1 2 3 4 5 6
Time Complexity : O(n)
This article is contributed by Geetanjali Gaddam . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.[/sourcecode]
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Level order traversal line by line | Set 3 (Using One Queue)
- Print level order traversal line by line | Set 1
- Level order traversal of Binary Tree using Morris Traversal
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Connect Nodes at same Level (Level Order Traversal)
- Flatten Binary Tree in order of Level Order Traversal
- Insertion in n-ary tree in given order and Level order traversal
- Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
- Check if two trees are mirror of each other using level order traversal
- Level order traversal with direction change after every two levels
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Construct BST from its given level order traversal | Set-2
- Level order traversal in spiral form | Using one stack and one queue
- Zig Zag Level order traversal of a tree using single array
- Density of Binary Tree using Level Order Traversal
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Level order traversal in spiral form | Using Deque
- Level order traversal in spiral form using stack and multimap
- Deletion of a given node K in a Binary Tree using Level Order Traversal
- Level order traversal in spiral form