Zig-Zag level order traversal of Binary Tree after every K levels
Given a binary tree and an integer K, the task is to print the level order traversal in such a way that first K levels are printed from left to right, next K levels are printed from right to left, then next K levels are from left to right and so on.
Input: K = 1
/ \ /
4 9 8
4 9 8
Explanation: In the above example, first level is printed from left to right
and the second level is printed from right to left, and then last level is
printed from left to right.
Input: K = 3
/ \ / \
4 5 6 7
/ \ / \ /
8 9 10 11 12
/ \ /
13 14 15
4 5 6 7
12 11 10 9 8
15 14 13
Explanation: In the above example, first 3 levels are printed from left to right
and the last 2 levels are printed from right to left.
Approach: The solution to the problem is based on the following idea:
Start performing level order traversal on the tree from the left most end. After every K level, change the direction of printing the elements.
For this use stack. When the levels are to be printed from the right keep those values in stack and print the stack elements one by one from top. Because of the last in first out property of stack the elements would printed in reverse order.
Follow the steps mentioned below to implement the above idea:
- Use queue to perform level order traversal.
- In each level:
- If it is to be printed from the left, print them and push their child nodes in the queue.
- If this level is to be printed from the right side push the elements in a stack and print them after the whole level is traversed.
- If K levels are covered change the direction of printing from the next one.
Below is the implementation of the above approach.
1 2 3 4 5 6 7 12 11 10 9 8 15 14 13
Time Complexity: O(N) where N is number of nodes
Auxiliary Space: O(N)
Please Login to comment...