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
- Level order traversal in spiral form
- Check if two trees are mirror of each other using level order traversal
- Recursive Approach to find nth node from the end in the linked list
- Recursive approach for alternating split of Linked List
- Recursive insertion and traversal linked list
- Print all nodes between two given levels in Binary Tree
- Inorder predecessor and successor for a given key in BST | Iterative Approach
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Recursive Functions
- Recursive Implementation of atoi()
- Recursive Insertion Sort
- Recursive Bubble Sort
- Modular exponentiation (Recursive)
- Recursive program to generate power set
- Bitwise recursive addition of two integers
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.