Given a binary tree, print the level order traversal in such a way that first two levels are printed from left to right, next two levels are printed from right to left, then next two from left to right and so on. So, the problem is to reverse the direction of level order traversal of the binary tree after every two levels.
Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / \ / \ / \ 8 9 3 1 4 2 7 2 / / \ \ 16 17 18 19 Output: 1 2 3 7 6 5 4 2 7 2 4 1 3 9 8 16 17 18 19 In the above example, the first two levels are printed from left to right, next two levels are printed from right to left, and then the last level is printed from left to right.
Approach: In the previous post, level order traversal using queue and stack has been done to print the elements. A recursive method has been used over here to print the elements in every level. Traverse every level in the tree, for every level, check the direction. Use a flag to know the direction of traversal in the tree. If the flag is set to true, print the nodes from right to left in the particular level. If the flag is set to false, print the nodes in that level from left to right. Initially, the flag is set to False, after every 2 levels, flag changes its value to true and vice versa.
Below is the implementation of the above approach.
1 2 3 7 6 5 4 2 7 2 4 1 3 9 8 16 17 18 19
- Flatten Binary Tree in order of Level Order Traversal
- Insertion in n-ary tree in given order and Level order traversal
- Print even positioned nodes of even levels in level order of the given binary tree
- Print the last k nodes of the linked list in reverse order | Recursive approach
- Level order traversal in spiral form
- Reverse Level Order traversal in spiral form
- Check if two trees are mirror of each other using level order traversal
- Recursive Program to Print extreme nodes of each level of Binary Tree in alternate order
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Flatten binary tree in order of post-order traversal
- Count all sub-sequences having product <= K - Recursive approach
- Recursive Approach to find nth node from the end in the linked list
- Modify contents of Linked List - Recursive approach
- Recursive approach for alternating split of Linked List
- Recursive insertion and traversal linked list
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.