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:

Output:

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:
C++
// C++ Program to convert a BST into a Min-Heap
// in O(n) time and in-place
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int val) {
data = val;
left = nullptr;
right = nullptr;
}
};
// Utility function to print Min-Heap
// level by level
void printLevelOrder(Node *root) {
// Base Case
if (root == nullptr)
return;
// Create an empty queue for level
// order traversal
queue<Node *> q;
q.push(root);
while (!q.empty()) {
int nodeCount = q.size();
while (nodeCount > 0) {
Node *node = q.front();
cout << node->data << " ";
q.pop();
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
nodeCount--;
}
cout << endl;
}
}
// A simple recursive function to convert a given
// Binary Search Tree to Sorted Linked List
Node *bstToSortedLL(Node *root, Node *head) {
// Base cases
if (root == nullptr)
return head;
// Recursively convert right subtree
head = bstToSortedLL(root->right, head);
// insert root into linked list
root->right = head;
// Change left pointer of previous
// head to point to NULL
if (head != nullptr)
head->left = nullptr;
head = root;
// Recursively convert left subtree
return bstToSortedLL(root->left, head);
}
// Function to convert a sorted Linked
// List to Min-Heap
Node *sortedLLToMinHeap(Node *head) {
// Base Case
if (head == nullptr)
return nullptr;
queue<Node *> q;
Node *root = head;
head = head->right;
root->right = nullptr;
q.push(root);
// Run until the end of linked
// list is reached
while (head) {
// Take the parent node from the queue and
// remove it from the queue
Node *parent = q.front();
q.pop();
// Take next two nodes from the linked list and
// add them as children of the current parent node
// Also push them into the queue so that they
// will be parents to the future nodes
Node *leftChild = head;
head = head->right;
leftChild->right = nullptr;
q.push(leftChild);
// Assign the left child of parent
parent->left = leftChild;
if (head) {
Node *rightChild = head;
head = head->right;
rightChild->right = nullptr;
q.push(rightChild);
// Assign the right child of parent
parent->right = rightChild;
}
}
return root;
}
// Function to convert BST into a Min-Heap
// without using any extra space
Node *bstToMinHeap(Node *root) {
// Head of Linked List
Node *head = nullptr;
// Convert a given BST to Sorted
// Linked List
head = bstToSortedLL(root, head);
root = nullptr;
// Convert Sorted Linked List to Min-Heap
return sortedLLToMinHeap(head);
}
int main() {
// Constructing below tree
// 8
// / \
// 4 12
// / \ / \
// 2 6 10 14
//
Node *root = new Node(8);
root->left = new Node(4);
root->right = new Node(12);
root->right->left = new Node(10);
root->right->right = new Node(14);
root->left->left = new Node(2);
root->left->right = new Node(6);
root = bstToMinHeap(root);
printLevelOrder(root);
return 0;
}
Java
// Java Program to convert a BST into a
// Min-Heap in O(n) time and in-place
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
public Node(int val) {
data = val;
left = null;
right = null;
}
}
class GfG {
// Utility function to print Min-Heap level by level
static void printLevelOrder(Node root) {
// Base Case
if (root == null) return;
// Create an empty queue for level
// order traversal
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int nodeCount = q.size();
while (nodeCount > 0) {
Node node = q.poll();
System.out.print(node.data + " ");
if (node.left != null)
q.add(node.left);
if (node.right != null)
q.add(node.right);
nodeCount--;
}
System.out.println();
}
}
// A simple recursive function to convert a given
// Binary Search Tree to Sorted Linked List
static Node bstToSortedLL(Node root, Node head) {
if (root == null)
return head;
// Recursively convert right subtree
head = bstToSortedLL(root.right, head);
// Insert root into linked list
root.right = head;
// Change left pointer of previous
// head to point to NULL
if (head != null)
head.left = null;
head = root;
// Recursively convert left subtree
return bstToSortedLL(root.left, head);
}
// Function to convert a sorted Linked
// List to Min-Heap
static Node sortedLLToMinHeap(Node head) {
// Base Case
if (head == null)
return null;
Queue<Node> q = new LinkedList<>();
Node root = head;
head = head.right;
root.right = null;
q.add(root);
// Run until the end of linked list
// is reached
while (head != null) {
// Take the parent node from the queue and
// remove it from the queue
Node parent = q.poll();
// Take next two nodes from the linked list and
// add them as children of the current parent node
// Also push them into the queue so that they
// will be parents to the future nodes
Node leftChild = head;
head = head.right;
leftChild.right = null;
q.add(leftChild);
// Assign the left child of parent
parent.left = leftChild;
if (head != null) {
Node rightChild = head;
head = head.right;
rightChild.right = null;
q.add(rightChild);
// Assign the right child of parent
parent.right = rightChild;
}
}
return root;
}
// Function to convert BST into a Min-Heap
static Node bstToMinHeap(Node root) {
Node head = null;
// Convert a given BST to Sorted
// Linked List
head = bstToSortedLL(root, head);
root = null;
// Convert Sorted Linked List to Min-Heap
return sortedLLToMinHeap(head);
}
public static void main(String[] args) {
// Constructing below tree
// 8
// / \
// 4 12
// / \ / \
// 2 6 10 14
Node root = new Node(8);
root.left = new Node(4);
root.right = new Node(12);
root.right.left = new Node(10);
root.right.right = new Node(14);
root.left.left = new Node(2);
root.left.right = new Node(6);
root = bstToMinHeap(root);
printLevelOrder(root);
}
}
Python
# Python Program to convert a BST into a
# Min-Heap in O(n) time and in-place
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
# Utility function to print Min-Heap
# level by level
def printLevelOrder(root):
# Base Case
if root is None:
return
# Create an empty queue for level
# order traversal
queue = []
queue.append(root)
while queue:
nodeCount = len(queue)
while nodeCount > 0:
node = queue.pop(0)
print(node.data, end=" ")
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
nodeCount -= 1
print()
# recursive function to convert a given
# Binary Search Tree to Sorted Linked List
def bstToSortedLL(root, head):
if root is None:
return head
# Recursively convert right subtree
head = bstToSortedLL(root.right, head)
root.right = head
if head is not None:
head.left = None
head = root
# Recursively convert left subtree
return bstToSortedLL(root.left, head)
# Function to convert a sorted Linked
# List to Min-Heap
def sortedLLToMinHeap(head):
# Base Case
if head is None:
return None
queue = []
root = head
head = head.right
root.right = None
queue.append(root)
# Run until the end of linked list
# is reached
while head:
# Take the parent node from the queue
# and remove it
parent = queue.pop(0)
# Take next two nodes from the linked list and
# add them as children of the current parent node
# Also push them into the queue so that they will
# be parents to the future nodes
leftChild = head
head = head.right
leftChild.right = None
queue.append(leftChild)
parent.left = leftChild
if head:
rightChild = head
head = head.right
rightChild.right = None
queue.append(rightChild)
# Assign the right child of parent
parent.right = rightChild
return root
# Function to convert BST into a Min-Heap
def bstToMinHeap(root):
head = None
# Convert a given BST to Sorted
# Linked List
head = bstToSortedLL(root, head)
root = None
# Convert Sorted Linked List to Min-Heap
return sortedLLToMinHeap(head)
# Constructing below tree
# 8
# / \
# 4 12
# / \ / \
# 2 6 10 14
#
root = Node(8)
root.left = Node(4)
root.right = Node(12)
root.right.left = Node(10)
root.right.right = Node(14)
root.left.left = Node(2)
root.left.right = Node(6)
root = bstToMinHeap(root)
printLevelOrder(root)
C#
// C# Program to convert a BST into a Min-Heap
// in O(n) time and in-place
using System;
using System.Collections.Generic;
class Node {
public int Data;
public Node Left, Right;
public Node(int val) {
Data = val;
Left = null;
Right = null;
}
}
class GfG {
// Utility function to print Min-Heap level by level
static void PrintLevelOrder(Node root) {
// Base Case
if (root == null) return;
// Create an empty queue for level
// order traversal
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while (q.Count > 0) {
int nodeCount = q.Count;
while (nodeCount > 0) {
Node node = q.Dequeue();
Console.Write(node.Data + " ");
if (node.Left != null)
q.Enqueue(node.Left);
if (node.Right != null)
q.Enqueue(node.Right);
nodeCount--;
}
Console.WriteLine();
}
}
// A simple recursive function to convert a given
// Binary Search Tree to Sorted Linked List
static Node BstToSortedLL(Node root, Node head) {
// Base cases
if (root == null)
return head;
// Recursively convert right subtree
head = BstToSortedLL(root.Right, head);
root.Right = head;
// Change left pointer of previous
// head to point to NULL
if (head != null)
head.Left = null;
head = root;
// Recursively convert
//left subtree
return BstToSortedLL(root.Left, head);
}
// Function to convert a sorted Linked
// List to Min-Heap
static Node SortedLLToMinHeap(Node head) {
// Base Case
if (head == null)
return null;
Queue<Node> q = new Queue<Node>();
Node root = head;
head = head.Right;
root.Right = null;
q.Enqueue(root);
// Run until the end of linked
// list is reached
while (head != null) {
// Take the parent node from the queue and
// remove it from the queue
Node parent = q.Dequeue();
// Take next two nodes from the linked list and
// add them as children of the current parent node
// Also push them into the queue so that they
// will be parents to the future nodes
Node leftChild = head;
head = head.Right;
leftChild.Right = null;
q.Enqueue(leftChild);
parent.Left = leftChild;
if (head != null) {
Node rightChild = head;
head = head.Right;
rightChild.Right = null;
q.Enqueue(rightChild);
// Assign the right child
// of parent
parent.Right = rightChild;
}
}
return root;
}
// Function to convert BST into a Min-Heap without
// using any extra space
static Node BstToMinHeap(Node root) {
Node head = null;
// Convert a given BST to Sorted
// Linked List
head = BstToSortedLL(root, head);
root = null;
// Convert Sorted Linked List
// to Min-Heap
return SortedLLToMinHeap(head);
}
static void Main(string[] args) {
// Constructing below tree
// 8
// / \
// 4 12
// / \ / \
// 2 6 10 14
//
Node root = new Node(8);
root.Left = new Node(4);
root.Right = new Node(12);
root.Right.Left = new Node(10);
root.Right.Right = new Node(14);
root.Left.Left = new Node(2);
root.Left.Right = new Node(6);
root = BstToMinHeap(root);
PrintLevelOrder(root);
}
}
JavaScript
// JavaScript Program to convert a BST into
// a Min-Heap in O(n) time and in-place
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
// Utility function to print Min-Heap
// level by level
function printLevelOrder(root) {
// Base Case
if (root === null) return;
// Create an empty queue for
// level order traversal
const queue = [];
queue.push(root);
while (queue.length > 0) {
let nodeCount = queue.length;
while (nodeCount > 0) {
const node = queue.shift();
console.log(node.data + " ");
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
nodeCount--;
}
console.log();
}
}
// Recursive function to convert a given
// Binary Search Tree to Sorted Linked List
function bstToSortedLL(root, head) {
// Base cases
if (root === null) return head;
// Recursively convert right subtree
head = bstToSortedLL(root.right, head);
root.right = head;
if (head !== null) head.left = null;
head = root;
return bstToSortedLL(root.left, head);
}
// Function to convert a sorted Linked
// List to Min-Heap
function sortedLLToMinHeap(head) {
// Base Case
if (head === null) return null;
const queue = [];
const root = head;
head = head.right;
root.right = null;
queue.push(root);
// Run until the end of linked
// list is reached
while (head) {
// Take the parent node from the queue
// and remove it
const parent = queue.shift();
// Take next two nodes from the linked list and
// add them as children of the current parent node
// Also push them into the queue so that they will
// be parents to the future nodes
const leftChild = head;
head = head.right;
leftChild.right = null;
queue.push(leftChild);
parent.left = leftChild;
if (head) {
const rightChild = head;
head = head.right;
rightChild.right = null;
queue.push(rightChild);
// Assign the right child of parent
parent.right = rightChild;
}
}
return root;
}
// Function to convert BST into a Min-Heap
function bstToMinHeap(root) {
let head = null;
// Convert a given BST to Sorted
// Linked List
head = bstToSortedLL(root, head);
root = null;
// Convert Sorted Linked List
// to Min-Heap
return sortedLLToMinHeap(head);
}
// Constructing below tree
// 8
// / \
// 4 12
// / \ / \
// 2 6 10 14
//
let root = new Node(8);
root.left = new Node(4);
root.right = new Node(12);
root.right.left = new Node(10);
root.right.right = new Node(14);
root.left.left = new Node(2);
root.left.right = new Node(6);
root = bstToMinHeap(root);
printLevelOrder(root);
Time Complexity: O(n), where n is the number of nodes in BST.
Auxiliary Space: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem