Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
Given a Binary Search Tree, the task is to print the nodes of the BST in the following order:
- If the BST contains levels numbered from 1 to N then, the printing order is level 1, level N, level 2, level N – 1, and so on.
- The top-level order (1, 2, …) nodes are printed from left to right, while the bottom level order (N, N-1, …) nodes are printed from right to left.
Approach: To solve the problem, the idea is to store the nodes of BST in ascending and descending order of levels and node values and print all the nodes of the same level alternatively between ascending and descending order. Follow the steps below to solve the problem:
- Initialize a Min Heap and a Max Heap to store the nodes in ascending and descending order of level and node values respectively.
- Perform a level order traversal on the given BST to store the nodes in the respective priority queues.
- Print all the nodes of each level one by one from the Min Heap followed by the Max Heap alternately.
- If any level in the Min Heap or Max Heap is found to be already printed, skip to the next level.
Below is the implementation of the above approach:
25 48 38 28 12 5 20 36 40 30 22 10
Time Complexity: O(V log(V)), where V denotes the number of vertices in the given Binary Tree
Auxiliary Space: O(V)