Print Binary Search Tree in Min Max Fashion
Given a Binary Search Tree (BST), the task is to print the BST in min-max fashion.
What is min-max fashion?
A min-max fashion means you have to print the maximum node first then the minimum then the second maximum then the second minimum and so on.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: 100 / \ 20 500 / \ 10 30 \ 40 Output: 10 500 20 100 30 40 Input: 40 / \ 20 50 / \ \ 10 35 60 / / 25 55 Output: 10 60 20 55 25 50 35 40
- Create an array inorder and store the inorder traversal of the givrn binary search tree.
- Since the inorder traversal of the binary search tree is sorted in ascending, initialise i = 0 and j = n – 1.
- Print inorder[i] and update i = i + 1.
- Print inorder[j] and update j = j – 1.
- Repeat steps 3 and 4 until all the elements have been printed.
Below is the implementation of the above approach:
20 80 30 70 40 60 50