VOOZH about

URL: https://www.geeksforgeeks.org/dsa/convert-bst-min-heap/

⇱ Convert BST to Min Heap - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert BST to Min Heap

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. 

Approach:

The idea is to store the inorder traversal of the BST in array and then do preorder traversal of the BST and while doing preorder traversal copy the values of inorder traversal into the current node, as copying the sorted elements while doing preorder traversal will make sure that a min-heap is constructed with the condition that all the values in the left subtree of a node are less than all the values in the right subtree of the node.

Follow the below steps to solve the problem:

  • 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 of the BST.

Below is the implementation of the above approach:


Output
1 2 3 4 5 6 7 

Time Complexity:O(n), since inorder traversal and preorder filling both take O(n), where n is the number of nodes in the tree.
Auxiliary Space: O(n), space is used for storing the inorder traversal in the array, also recursion stack uses O(h) space, where h is the height of the tree (O(log n) for balanced trees, O(n) for skewed trees).

Comment
Article Tags: