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>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Function to perform inorder traversal of BST// and store the node values in a vectorvoidinorderTraversal(Node*root,vector<int>&inorderArr){if(root==nullptr){return;}// Traverse the left subtree Store the current // node value Traverse the right subtreeinorderTraversal(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 nodesvoidpreorderFill(Node*root,vector<int>&inorderArr,int&index){if(root==nullptr){return;}// Copy the next element from the inorder arrayroot->data=inorderArr[index++];// Fill left and right subtreepreorderFill(root->left,inorderArr,index);preorderFill(root->right,inorderArr,index);}// Function to convert BST to Min HeapvoidconvertBSTtoMinHeap(Node*root){vector<int>inorderArr;// Step 1: Perform inorder traversal // to store values in sorted orderinorderTraversal(root,inorderArr);intindex=0;// Step 2: Perform preorder traversal and // fill nodes with inorder valuespreorderFill(root,inorderArr,index);}// Function to print preorder traversal of the treevoidpreorderPrint(Node*root){if(root==nullptr){return;}cout<<root->data<<" ";preorderPrint(root->left);preorderPrint(root->right);}intmain(){// Constructing the Binary Search Tree (BST)// 4// / \ // 2 6// / \ / \ // 1 3 5 7Node*root=newNode(4);root->left=newNode(2);root->right=newNode(6);root->left->left=newNode(1);root->left->right=newNode(3);root->right->left=newNode(5);root->right->right=newNode(7);convertBSTtoMinHeap(root);preorderPrint(root);return0;}
Java
// Java implementation to convert the given// BST to Min Heapimportjava.util.ArrayList;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to perform inorder traversal of the BST// and store node values in an ArrayListstaticvoidinorderTraversal(Noderoot,ArrayList<Integer>inorderArr){if(root==null){return;}// Traverse the left subtree, store // the current node value,// and traverse the right subtreeinorderTraversal(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 nodesstaticvoidpreorderFill(Noderoot,ArrayList<Integer>inorderArr,int[]index){if(root==null){return;}// Copy the next element from the inorder arrayroot.data=inorderArr.get(index[0]++);// Fill left and right subtreepreorderFill(root.left,inorderArr,index);preorderFill(root.right,inorderArr,index);}// Function to convert BST to Min HeapstaticvoidconvertBSTtoMinHeap(Noderoot){ArrayList<Integer>inorderArr=newArrayList<>();// Step 1: Perform inorder traversal to// store values in sorted orderinorderTraversal(root,inorderArr);// Using array to keep index as a referenceint[]index={0};// Step 2: Perform preorder traversal and // fill nodes with inorder valuespreorderFill(root,inorderArr,index);}staticvoidpreorderPrint(Noderoot){if(root==null){return;}System.out.print(root.data+" ");preorderPrint(root.left);preorderPrint(root.right);}publicstaticvoidmain(String[]args){// Constructing the Binary Search Tree (BST)// 4// / \// 2 6// / \ / \// 1 3 5 7Noderoot=newNode(4);root.left=newNode(2);root.right=newNode(6);root.left.left=newNode(1);root.left.right=newNode(3);root.right.left=newNode(5);root.right.right=newNode(7);convertBSTtoMinHeap(root);preorderPrint(root);}}
Python
# Python implementation to convert the given# BST to Min HeapclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Function to perform inorder traversal of the BST# and store the node values in a listdefinorder_traversal(root,inorder_arr):ifrootisNone:return# Traverse the left subtree, store the current# node value, and traverse the right subtreeinorder_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 nodesdefpreorder_fill(root,inorder_arr,index):ifrootisNone:returnindex# Copy the next element from the inorder listroot.data=inorder_arr[index]index+=1# Fill left and right subtreeindex=preorder_fill(root.left,inorder_arr,index)index=preorder_fill(root.right,inorder_arr,index)returnindex# Function to convert BST to Min HeapdefbstToMinHeap(root):inorder_arr=[]# Step 1: Perform inorder traversal to # store values in sorted orderinorder_traversal(root,inorder_arr)# Step 2: Perform preorder traversal # and fill nodes with inorder valuespreorder_fill(root,inorder_arr,0)# Function to print preorder traversal of the treedefpreorder_print(root):ifrootisNone:returnprint(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 7root=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 HeapusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to perform inorder traversal of the BST// and store the node values in a ListstaticvoidInorderTraversal(Noderoot,List<int>inorderArr){if(root==null){return;}// Traverse the left subtree, store the // current node value, and traverse // the right subtreeInorderTraversal(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 nodesstaticvoidPreorderFill(Noderoot,List<int>inorderArr,refintindex){if(root==null){return;}// Copy the next element from the inorder listroot.data=inorderArr[index++];// Fill left and right subtreePreorderFill(root.left,inorderArr,refindex);PreorderFill(root.right,inorderArr,refindex);}// Function to convert BST to Min HeapstaticvoidConvertBSTToMinHeap(Noderoot){List<int>inorderArr=newList<int>();// Step 1: Perform inorder traversal to// store values in sorted orderInorderTraversal(root,inorderArr);intindex=0;// Step 2: Perform preorder traversal // and fill nodes with inorder valuesPreorderFill(root,inorderArr,refindex);}// Function to print preorder traversal of the treestaticvoidPreorderPrint(Noderoot){if(root==null){return;}Console.Write(root.data+" ");PreorderPrint(root.left);PreorderPrint(root.right);}publicstaticvoidMain(){// Constructing the Binary Search Tree (BST)// 4// / \// 2 6// / \ / \// 1 3 5 7Noderoot=newNode(4);root.left=newNode(2);root.right=newNode(6);root.left.left=newNode(1);root.left.right=newNode(3);root.right.left=newNode(5);root.right.right=newNode(7);ConvertBSTToMinHeap(root);PreorderPrint(root);}}
JavaScript
// Javascript implementation to convert the given// BST to Min HeapclassNode{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 arrayfunctioninorderTraversal(root,inorderArr){if(root===null){return;}// Traverse the left subtree, store the // current node value, and traverse// the right subtreeinorderTraversal(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 nodesfunctionpreorderFill(root,inorderArr,index){if(root===null){returnindex;}// Copy the next element from the inorder arrayroot.data=inorderArr[index];index+=1;// Fill left and right subtreeindex=preorderFill(root.left,inorderArr,index);index=preorderFill(root.right,inorderArr,index);returnindex;}// Function to convert BST to Min HeapfunctionconvertBSTtoMinHeap(root){letinorderArr=[];// Step 1: Perform inorder traversal to // store values in sorted orderinorderTraversal(root,inorderArr);// Step 2: Perform preorder traversal // and fill nodes with inorder valuespreorderFill(root,inorderArr,0);}// Function to print preorder traversal of the treefunctionpreorderPrint(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 7letroot=newNode(4);root.left=newNode(2);root.right=newNode(6);root.left.left=newNode(1);root.left.right=newNode(3);root.right.left=newNode(5);root.right.right=newNode(7);convertBSTtoMinHeap(root);preorderPrint(root);
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).