Given a binary search tree which is also a complete binary tree. The problem is to convert the given BST into a Min Heap with the condition that all the values in the left subtree of a node should be less than all the values in the right subtree of the node. This condition is applied on all the nodes in the so converted Min Heap.
Input : 4 / \ 2 6 / \ / \ 1 3 5 7 Output : 1 / \ 2 5 / \ / \ 3 4 6 7 The given BST has been transformed into a Min Heap. All the nodes in the Min Heap satisfies the given condition, that is, values in the left subtree of a node should be less than the values in the right subtree of the node.
- Create an array arr of size n, where n is the number of nodes in the given BST.
- Perform the inorder traversal of the BST and copy the node values in the arr in sorted order.
- Now perform the preorder traversal of the tree.
- While traversing the root during the preorder traversal, one by one copy the values from the array arr to the nodes.
Preorder Traversal: 1 2 3 4 5 6 7
Time Complexity: O(n)
Auxiliary Space: O(n)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.
- Convert min Heap to max Heap
- Convert BST into a Min-Heap without using array
- Difference between Binary Heap, Binomial Heap and Fibonacci Heap
- Heap Sort for decreasing order using min heap
- Difference between Min Heap and Max Heap
- Convert BST to Max Heap
- Convert a normal BST to Balanced BST
- Why is Binary Heap Preferred over BST for Priority Queue?
- Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Merge k sorted linked lists | Set 2 (Using Min Heap)
- Print all nodes less than a value x in a Min Heap.
- Maximum element in min heap
- Fibonacci Heap - Deletion, Extract min and Decrease key
- K’th Least Element in a Min-Heap
- Maximise the number of toys that can be purchased with amount K using min Heap
- Merge two sorted arrays in constant space using Min Heap
- Min Heap in Python
- Complexity analysis of various operations of Binary Min Heap
- k largest(or smallest) elements in an array | added Min Heap method
Improved By : PranchalKatiyar