Convert BST into a Min-Heap without using array
Last Updated :
17 Oct, 2024
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
Binary Search Tree A Binary Search Tree (BST) is a type of binary tree data structure in which each node contains a unique key and satisfies a specific ordering property:All nodes in the left subtree of a node contain values strictly less than the nodeâs value. All nodes in the right subtree of a node contain values s
4 min read
Introduction to Binary Search Tree Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
3 min read
Applications of BST Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward.The left subtree of a node contains only node
3 min read
Applications, Advantages and Disadvantages of Binary Search Tree A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
2 min read
Insertion in Binary Search Tree (BST) Given a BST, the task is to insert a new node in this BST.Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is fo
15 min read
Searching in Binary Search Tree (BST) Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
7 min read
Deletion in Binary Search Tree (BST) Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios:Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BSTDeleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node w
10 min read
Binary Search Tree (BST) Traversals â Inorder, Preorder, Post Order Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree. Input: A Binary Search TreeOutput: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 1
10 min read
Balance a Binary Search Tree Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height.Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height.Input: Output: Explanation: The above u
10 min read
Self-Balancing Binary Search Trees Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
4 min read