Level order traversal with direction change after every two levels | Recursive Approach
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
- Time Complexity : O(N)
- Auxiliary Space: O(N)