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.
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:
C++
// C++ implementation to convert the given
// BST to Min Heap
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Function to perform inorder traversal of BST
// and store the node values in a vector
void inorderTraversal(Node* root,
vector<int>& inorderArr) {
if (root == nullptr) {
return;
}
// Traverse the left subtree Store the current
// node value Traverse the right subtree
inorderTraversal(root->left, inorderArr);
inorderArr.push_back(root->data);
inorderTraversal(root->right, inorderArr);
}
// Function to perform preorder traversal of the tree
// and copy the values from the inorder array to nodes
void preorderFill(Node* root, vector<int>& inorderArr,
int& index) {
if (root == nullptr) {
return;
}
// Copy the next element from the inorder array
root->data = inorderArr[index++];
// Fill left and right subtree
preorderFill(root->left, inorderArr, index);
preorderFill(root->right, inorderArr, index);
}
// Function to convert BST to Min Heap
void convertBSTtoMinHeap(Node* root) {
vector<int> inorderArr;
// Step 1: Perform inorder traversal
// to store values in sorted order
inorderTraversal(root, inorderArr);
int index = 0;
// Step 2: Perform preorder traversal and
// fill nodes with inorder values
preorderFill(root, inorderArr, index);
}
// Function to print preorder traversal of the tree
void preorderPrint(Node* root) {
if (root == nullptr) {
return;
}
cout << root->data << " ";
preorderPrint(root->left);
preorderPrint(root->right);
}
int main() {
// Constructing the Binary Search Tree (BST)
// 4
// / \
// 2 6
// / \ / \
// 1 3 5 7
Node* root = new Node(4);
root->left = new Node(2);
root->right = new Node(6);
root->left->left = new Node(1);
root->left->right = new Node(3);
root->right->left = new Node(5);
root->right->right = new Node(7);
convertBSTtoMinHeap(root);
preorderPrint(root);
return 0;
}
Java
// Java implementation to convert the given
// BST to Min Heap
import java.util.ArrayList;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to perform inorder traversal of the BST
// and store node values in an ArrayList
static void inorderTraversal(Node root,
ArrayList<Integer> inorderArr) {
if (root == null) {
return;
}
// Traverse the left subtree, store
// the current node value,
// and traverse the right subtree
inorderTraversal(root.left, inorderArr);
inorderArr.add(root.data);
inorderTraversal(root.right, inorderArr);
}
// Function to perform preorder traversal of the tree
// and copy the values from the inorder
// ArrayList to the nodes
static void preorderFill(Node root,
ArrayList<Integer> inorderArr, int[] index) {
if (root == null) {
return;
}
// Copy the next element from the inorder array
root.data = inorderArr.get(index[0]++);
// Fill left and right subtree
preorderFill(root.left, inorderArr, index);
preorderFill(root.right, inorderArr, index);
}
// Function to convert BST to Min Heap
static void convertBSTtoMinHeap(Node root) {
ArrayList<Integer> inorderArr
= new ArrayList<>();
// Step 1: Perform inorder traversal to
// store values in sorted order
inorderTraversal(root, inorderArr);
// Using array to keep index as a reference
int[] index = {0};
// Step 2: Perform preorder traversal and
// fill nodes with inorder values
preorderFill(root, inorderArr, index);
}
static void preorderPrint(Node root) {
if (root == null) {
return;
}
System.out.print(root.data + " ");
preorderPrint(root.left);
preorderPrint(root.right);
}
public static void main(String[] args) {
// Constructing the Binary Search Tree (BST)
// 4
// / \
// 2 6
// / \ / \
// 1 3 5 7
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(6);
root.left.left = new Node(1);
root.left.right = new Node(3);
root.right.left = new Node(5);
root.right.right = new Node(7);
convertBSTtoMinHeap(root);
preorderPrint(root);
}
}
Python
# Python implementation to convert the given
# BST to Min Heap
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to perform inorder traversal of the BST
# and store the node values in a list
def inorder_traversal(root, inorder_arr):
if root is None:
return
# Traverse the left subtree, store the current
# node value, and traverse the right subtree
inorder_traversal(root.left, inorder_arr)
inorder_arr.append(root.data)
inorder_traversal(root.right, inorder_arr)
# Function to perform preorder traversal of the tree
# and copy the values from the inorder list to the nodes
def preorder_fill(root, inorder_arr, index):
if root is None:
return index
# Copy the next element from the inorder list
root.data = inorder_arr[index]
index += 1
# Fill left and right subtree
index = preorder_fill(root.left, inorder_arr, index)
index = preorder_fill(root.right, inorder_arr, index)
return index
# Function to convert BST to Min Heap
def bstToMinHeap(root):
inorder_arr = []
# Step 1: Perform inorder traversal to
# store values in sorted order
inorder_traversal(root, inorder_arr)
# Step 2: Perform preorder traversal
# and fill nodes with inorder values
preorder_fill(root, inorder_arr, 0)
# Function to print preorder traversal of the tree
def preorder_print(root):
if root is None:
return
print(root.data, end=" ")
preorder_print(root.left)
preorder_print(root.right)
if __name__ == "__main__":
# Constructing the Binary Search Tree (BST)
# 4
# / \
# 2 6
# / \ / \
# 1 3 5 7
root = Node(4)
root.left = Node(2)
root.right = Node(6)
root.left.left = Node(1)
root.left.right = Node(3)
root.right.left = Node(5)
root.right.right = Node(7)
bstToMinHeap(root)
preorder_print(root)
C#
// C# implementation to convert the given
// BST to Min Heap
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to perform inorder traversal of the BST
// and store the node values in a List
static void InorderTraversal(Node root,
List<int> inorderArr) {
if (root == null) {
return;
}
// Traverse the left subtree, store the
// current node value, and traverse
// the right subtree
InorderTraversal(root.left, inorderArr);
inorderArr.Add(root.data);
InorderTraversal(root.right, inorderArr);
}
// Function to perform preorder traversal
// of the tree and copy the values from the inorder
// list to the nodes
static void PreorderFill(Node root,
List<int> inorderArr, ref int index) {
if (root == null) {
return;
}
// Copy the next element from the inorder list
root.data = inorderArr[index++];
// Fill left and right subtree
PreorderFill(root.left, inorderArr, ref index);
PreorderFill(root.right, inorderArr, ref index);
}
// Function to convert BST to Min Heap
static void ConvertBSTToMinHeap(Node root) {
List<int> inorderArr = new List<int>();
// Step 1: Perform inorder traversal to
// store values in sorted order
InorderTraversal(root, inorderArr);
int index = 0;
// Step 2: Perform preorder traversal
// and fill nodes with inorder values
PreorderFill(root, inorderArr, ref index);
}
// Function to print preorder traversal of the tree
static void PreorderPrint(Node root) {
if (root == null) {
return;
}
Console.Write(root.data + " ");
PreorderPrint(root.left);
PreorderPrint(root.right);
}
public static void Main() {
// Constructing the Binary Search Tree (BST)
// 4
// / \
// 2 6
// / \ / \
// 1 3 5 7
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(6);
root.left.left = new Node(1);
root.left.right = new Node(3);
root.right.left = new Node(5);
root.right.right = new Node(7);
ConvertBSTToMinHeap(root);
PreorderPrint(root);
}
}
JavaScript
// Javascript implementation to convert the given
// BST to Min Heap
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// Function to perform inorder traversal of the BST
// and store the node values in an array
function inorderTraversal(root, inorderArr) {
if (root === null) {
return;
}
// Traverse the left subtree, store the
// current node value, and traverse
// the right subtree
inorderTraversal(root.left, inorderArr);
inorderArr.push(root.data);
inorderTraversal(root.right, inorderArr);
}
// Function to perform preorder traversal of the tree
// and copy the values from the inorder
// array to the nodes
function preorderFill(root, inorderArr, index) {
if (root === null) {
return index;
}
// Copy the next element from the inorder array
root.data = inorderArr[index];
index += 1;
// Fill left and right subtree
index = preorderFill(root.left, inorderArr, index);
index = preorderFill(root.right, inorderArr, index);
return index;
}
// Function to convert BST to Min Heap
function convertBSTtoMinHeap(root) {
let inorderArr = [];
// Step 1: Perform inorder traversal to
// store values in sorted order
inorderTraversal(root, inorderArr);
// Step 2: Perform preorder traversal
// and fill nodes with inorder values
preorderFill(root, inorderArr, 0);
}
// Function to print preorder traversal of the tree
function preorderPrint(root) {
if (root === null) {
return;
}
console.log(root.data + " ");
preorderPrint(root.left);
preorderPrint(root.right);
}
// Constructing the Binary Search Tree (BST)
// 4
// / \
// 2 6
// / \ / \
// 1 3 5 7
let root = new Node(4);
root.left = new Node(2);
root.right = new Node(6);
root.left.left = new Node(1);
root.left.right = new Node(3);
root.right.left = new Node(5);
root.right.right = new Node(7);
convertBSTtoMinHeap(root);
preorderPrint(root);
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).
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