VOOZH about

URL: https://www.geeksforgeeks.org/dsa/in-place-convert-bst-into-a-min-heap/

⇱ Convert BST into a Min-Heap without using array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert BST into a Min-Heap without using array

Last Updated : 23 Jul, 2025

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 to all the nodes, in the resultant converted Min Heap. 

Examples:

Input: 

πŸ‘ Convert-BST-to-Min-Heap-1


Output:

πŸ‘ Convert-BST-to-Min-Heap-2


Explanation: 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. 

If we are allowed to use extra space, we can perform inorder traversal of the tree and store the keys in an auxiliary array. As we’re doing inorder traversal on a BST, array will be sorted. Finally, we construct a complete binary tree from the sorted array. We construct the binary tree level by level and from left to right by taking next minimum element from sorted array. The constructed binary tree will be a min-Heap. This solution works in O(n) time, but is not in-place. Please refer to Convert BST to Min Heap for implementation.

Approach:

The idea is to convert the binary search tree into a sorted linked list first. We can do this by traversing the BST in inorder fashion. We add nodes at the beginning of current linked list and update head of the list using pointer to head pointer. Since we insert at the beginning, to maintain sorted order, we first traverse the right subtree before the left subtree. i.e. do a reverse inorder traversal.

Finally we convert the sorted linked list into a min-Heap by setting the left and right pointers appropriately. We can do this by doing a Level order traversal of the partially built Min-Heap Tree using queue and traversing the linked list at the same time. At every step, we take the parent node from queue, make next two nodes of linked list as children of the parent node, and enqueue the next two nodes to queue. As the linked list is sorted, the min-heap property is maintained.

Below is the implementation of the above approach:


Output
2 
4 6 
8 10 12 14 

Time Complexity: O(n), where n is the number of nodes in BST.
Auxiliary Space: O(n)

Comment
Article Tags: