The Wayback Machine - https://web.archive.org/web/20240717024437/https://www.geeksforgeeks.org/convert-bst-min-heap/
Open In App

Convert BST to Min Heap

Last Updated : 06 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:       4
                /   \
              2     6
            /  \   /  \
          1   3  5    7  
Output:  1
               /   \
             2     5
           /  \   /  \
         3   4  6    7 
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: To solve the problem using this approach follow the below idea:

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 given 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;
 
// Structure of a node of BST
struct Node {
 
    int data;
    Node *left, *right;
};
 
/* Helper function that allocates a new node
   with the given data and NULL left and right
   pointers. */
struct Node* getNode(int data)
{
    struct Node* newNode = new Node;
    newNode->data = data;
    newNode->left = newNode->right = NULL;
    return newNode;
}
 
// function prototype for preorder traversal
// of the given tree
void preorderTraversal(Node*);
 
// function for the inorder traversal of the tree
// so as to store the node values in 'arr' in
// sorted order
void inorderTraversal(Node* root, vector<int>& arr)
{
    if (root == NULL)
        return;
 
    // first recur on left subtree
    inorderTraversal(root->left, arr);
 
    // then copy the data of the node
    arr.push_back(root->data);
 
    // now recur for right subtree
    inorderTraversal(root->right, arr);
}
 
// function to convert the given BST to MIN HEAP
// performs preorder traversal of the tree
void BSTToMinHeap(Node* root, vector<int> arr, int* i)
{
    if (root == NULL)
        return;
 
    // first copy data at index 'i' of 'arr' to
    // the node
    root->data = arr[++*i];
 
    // then recur on left subtree
    BSTToMinHeap(root->left, arr, i);
 
    // now recur on right subtree
    BSTToMinHeap(root->right, arr, i);
}
 
// utility function to convert the given BST to
// MIN HEAP
void convertToMinHeapUtil(Node* root)
{
    // vector to store the data of all the
    // nodes of the BST
    vector<int> arr;
    int i = -1;
 
    // inorder traversal to populate 'arr'
    inorderTraversal(root, arr);
 
    // BST to MIN HEAP conversion
    BSTToMinHeap(root, arr, &i;);
}
 
// function for the preorder traversal of the tree
void preorderTraversal(Node* root)
{
    if (!root)
        return;
 
    // first print the root's data
    cout << root->data << " ";
 
    // then recur on left subtree
    preorderTraversal(root->left);
 
    // now recur on right subtree
    preorderTraversal(root->right);
}
 
// Driver program to test above
int main()
{
    // BST formation
    struct Node* root = getNode(4);
    root->left = getNode(2);
    root->right = getNode(6);
    root->left->left = getNode(1);
    root->left->right = getNode(3);
    root->right->left = getNode(5);
    root->right->right = getNode(7);
 
    // Function call
    convertToMinHeapUtil(root);
    cout << "Preorder Traversal:" << endl;
    preorderTraversal(root);
 
    return 0;
}


Java




// Java implementation to convert the given
// BST to Min Heap
import java.util.ArrayList;
 
class Gfg {
 
    static class Node {
 
        int data;
        Node left, right;
 
        // Constructor
        Node()
        {
            this.data = 0;
            this.left = this.right = null;
        }
 
        Node(int data)
        {
            this.data = data;
            this.left = this.right = null;
        }
    }
 
    private static void preOrder(Node root)
    {
        if (root == null)
            return;
        System.out.print(root.data + " ");
        preOrder(root.left);
        preOrder(root.right);
    }
 
    private static void bstToArray(Node root,
                                   ArrayList<Integer> arr)
    {
        // ArrayLIst stores elements in inorder fashion
        if (root == null)
            return;
 
        bstToArray(root.left, arr);
 
        arr.add(root.data);
 
        bstToArray(root.right, arr);
    }
 
    static int index;
    private static void arrToMinHeap(Node root,
                                     ArrayList<Integer> arr)
    {
        if (root == null)
            return;
        root.data = arr.get(index++);
 
        arrToMinHeap(root.left, arr);
        arrToMinHeap(root.right, arr);
    }
    static void convertToMinHeap(Node root)
    {
        // initialize static index to zero
        index = 0;
        ArrayList<Integer> arr = new ArrayList<Integer>();
        bstToArray(root, arr);
 
        arrToMinHeap(root, arr);
    }
 
    // Driver's code
    public static void main(String[] args)
    {
 
        // BST formation
        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);
 
        System.out.print(
            "Preorder Traversal Before Conversion :"
            + "\n");
        preOrder(root);
 
        // Function call
        convertToMinHeap(root);
 
        System.out.print(
            "\nPreorder Traversal After Conversion :"
            + "\n");
        preOrder(root);
    }
}
 
// Contributed by : @mahi_07
 
/*
Tip : If interviewer ask not to use global index variable
you can use LinkedList Instead of ArrayList and  use
LinkedList's removeFirst() method So instead of this
        root.data = arr.get(index++);
    you can write
        root.data = list.removeFirst();
    Do not forget to initialize list in converttoMinHeap
function
*/


Python3




# Python3 implementation to convert the
# given BST to Min Heap
 
# structure of a node of BST
 
 
class Node:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# function for the inorder traversal
# of the tree so as to store the node
# values in 'arr' in sorted order
 
 
def inorderTraversal(root, arr):
    if root == None:
        return
 
    # first recur on left subtree
    inorderTraversal(root.left, arr)
 
    # then copy the data of the node
    arr.append(root.data)
 
    # now recur for right subtree
    inorderTraversal(root.right, arr)
 
# function to convert the given
# BST to MIN HEAP performs preorder
# traversal of the tree
 
 
def BSTToMinHeap(root, arr, i):
    if root == None:
        return
 
    # first copy data at index 'i' of
    # 'arr' to the node
    i[0] += 1
    root.data = arr[i[0]]
 
    # then recur on left subtree
    BSTToMinHeap(root.left, arr, i)
 
    # now recur on right subtree
    BSTToMinHeap(root.right, arr, i)
 
# utility function to convert the
# given BST to MIN HEAP
 
 
def convertToMinHeapUtil(root):
 
    # vector to store the data of
    # all the nodes of the BST
    arr = []
    i = [-1]
 
    # inorder traversal to populate 'arr'
    inorderTraversal(root, arr)
 
    # BST to MIN HEAP conversion
    BSTToMinHeap(root, arr, i)
 
# function for the preorder traversal
# of the tree
 
 
def preorderTraversal(root):
    if root == None:
        return
 
    # first print the root's data
    print(root.data, end=" ")
 
    # then recur on left subtree
    preorderTraversal(root.left)
 
    # now recur on right subtree
    preorderTraversal(root.right)
 
 
# Driver's Code
if __name__ == '__main__':
 
    # BST formation
    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)
 
    # Function call
    convertToMinHeapUtil(root)
    print("Preorder Traversal:")
    preorderTraversal(root)
 
# This code is contributed
# by PranchalK


C#




// C# implementation to convert the given
// BST to Min Heap
using System;
using System.Collections.Generic;
public class GFG {
 
    // structure of a node of BST
    public
 
        class Node {
        public int data;
        public Node left, right;
    };
 
    /* Helper function that allocates a new node
       with the given data and null left and right
       pointers. */
    static Node getNode(int data)
    {
        Node newNode = new Node();
        newNode.data = data;
        newNode.left = newNode.right = null;
        return newNode;
    }
 
    // function prototype for preorder traversal
    // of the given tree
 
    // function for the inorder traversal of the tree
    // so as to store the node values in 'arr' in
    // sorted order
    static void inorderTraversal(Node root)
    {
        if (root == null)
            return;
 
        // first recur on left subtree
        inorderTraversal(root.left);
 
        // then copy the data of the node
        arr.Add(root.data);
 
        // now recur for right subtree
        inorderTraversal(root.right);
    }
 
    // function to convert the given BST to MIN HEAP
    // performs preorder traversal of the tree
    static void BSTToMinHeap(Node root)
    {
        if (root == null)
            return;
 
        // first copy data at index 'i' of 'arr' to
        // the node
        root.data = arr[++i];
 
        // then recur on left subtree
        BSTToMinHeap(root.left);
 
        // now recur on right subtree
        BSTToMinHeap(root.right);
    }
    static List<int> arr = new List<int>();
    static int i;
 
    // utility function to convert the given BST to
    // MIN HEAP
    static void convertToMinHeapUtil(Node root)
    {
 
        // vector to store the data of all the
        // nodes of the BST
        i = -1;
 
        // inorder traversal to populate 'arr'
        inorderTraversal(root);
 
        // BST to MIN HEAP conversion
        BSTToMinHeap(root);
    }
 
    // function for the preorder traversal of the tree
    static void preorderTraversal(Node root)
    {
        if (root == null)
            return;
 
        // first print the root's data
        Console.Write(root.data + " ");
 
        // then recur on left subtree
        preorderTraversal(root.left);
 
        // now recur on right subtree
        preorderTraversal(root.right);
    }
 
    // Driver program to test above
    public static void Main(String[] args)
    {
 
        // BST formation
        Node root = getNode(4);
        root.left = getNode(2);
        root.right = getNode(6);
        root.left.left = getNode(1);
        root.left.right = getNode(3);
        root.right.left = getNode(5);
        root.right.right = getNode(7);
 
        convertToMinHeapUtil(root);
        Console.Write("Preorder Traversal:"
                      + "\n");
        preorderTraversal(root);
    }
}
 
// This code contributed by Rajput-Ji


Javascript




// JavaScript implementation to convert the given
      // BST to Min Heap
      // structure of a node of BST
      class Node {
        constructor() {
          this.data = 0;
          this.left = null;
          this.right = null;
        }
      }
 
      /* Helper function that allocates a new node
      with the given data and null left and right
      pointers. */
      function getNode(data) {
        var newNode = new Node();
        newNode.data = data;
        newNode.left = newNode.right = null;
        return newNode;
      }
 
      // function prototype for preorder traversal
      // of the given tree
 
      // function for the inorder traversal of the tree
      // so as to store the node values in 'arr' in
      // sorted order
      function inorderTraversal(root) {
        if (root == null) return;
 
        // first recur on left subtree
        inorderTraversal(root.left);
 
        // then copy the data of the node
        arr.push(root.data);
 
        // now recur for right subtree
        inorderTraversal(root.right);
      }
 
      // function to convert the given BST to MIN HEAP
      // performs preorder traversal of the tree
      function BSTToMinHeap(root) {
        if (root == null) return;
 
        // first copy data at index 'i' of 'arr' to
        // the node
        root.data = arr[++i];
 
        // then recur on left subtree
        BSTToMinHeap(root.left);
 
        // now recur on right subtree
        BSTToMinHeap(root.right);
      }
      var arr = [];
      var i;
 
      // utility function to convert the given BST to
      // MIN HEAP
      function convertToMinHeapUtil(root) {
        // vector to store the data of all the
        // nodes of the BST
        i = -1;
 
        // inorder traversal to populate 'arr'
        inorderTraversal(root);
 
        // BST to MIN HEAP conversion
        BSTToMinHeap(root);
      }
 
      // function for the preorder traversal of the tree
      function preorderTraversal(root) {
        if (root == null) {
          return;
        }
 
        // first print the root's data
        document.write(root.data + " ");
 
        // then recur on left subtree
        preorderTraversal(root.left);
 
        // now recur on right subtree
        preorderTraversal(root.right);
      }
 
      // Driver program to test above
      // BST formation
      var root = getNode(4);
      root.left = getNode(2);
      root.right = getNode(6);
      root.left.left = getNode(1);
      root.left.right = getNode(3);
      root.right.left = getNode(5);
      root.right.right = getNode(7);
 
      convertToMinHeapUtil(root);
      document.write("Preorder Traversal: ");
      preorderTraversal(root);


Output

Preorder Traversal:
1 2 3 4 5 6 7 

Time Complexity: O(N) 
Auxiliary Space: O(N)   

 



Previous Article
Next Article

Similar Reads

Convert Min Heap to Max Heap
Given an array representation of min Heap, convert it to max Heap. Examples: Input: arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9} 3 / \ 5 9 / \ / \ 6 8 20 10 / \ /12 18 9 Output: arr[] = {20, 18, 10, 12, 9, 9, 3, 5, 6, 8} 20 / \ 18 10 / \ / \ 12 9 9 3 / \ /5 6 8 Input: arr[] = {3, 4, 8, 11, 13}Output: arr[] = {13, 11, 8, 4, 3} Approach: To solve the p
10 min read
Convert BST into a Min-Heap without using array
Given a Binary Search Tree, convert it into a Min-Heap containing the same elements in O(n) time. Do this in-place. Input: Binary Search Tree 8 / \ 4 12 / \ / \ 2 6 10 14 Output - Min Heap 2 / \ 4 6 / \ / \ 8 10 12 14 [Or any other tree that follows Min Heap properties and has same keys] If we are allowed to use extra space, we can perform inorder
15+ min read
Difference between Binary Heap, Binomial Heap and Fibonacci Heap
Binary Heap:A Binary Heap is a Binary Tree with following properties. It’s a complete binary tree i.e., all levels are completely filled except possibly the last level and the last level has all keys as left as possible. This property of Binary Heap makes them suitable to be stored in an array. A Binary Heap is either Min Heap or Max Heap. In a Min
2 min read
Heap Sort for decreasing order using min heap
Given an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1} Output : arr[] = {10, 5, 3, 1} Input : arr[] = {1, 50, 100, 25} Output : arr[] = {100, 50, 25, 1} Prerequisite: Heap sort using min heap. Algorithm : Build a min heap from the input data. At this point, the smallest item is stored
13 min read
Difference between Min Heap and Max Heap
A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Since a heap is a complete binary tree, a heap with N nodes has log N height. It is useful to remove the highest or lowest priority element. It is typically represented as an array. There are two types of Heaps in the data structure. Min-HeapIn a Min-Heap the
3 min read
Convert BST to Max Heap
Given a Binary Search Tree which is also a Complete Binary Tree. The problem is to convert a given BST into a Special Max 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 so-converted Max Heap. Examples: In
15+ min read
When building a Heap, is the structure of Heap unique?
What is Heap? A heap is a tree based data structure where the tree is a complete binary tree that maintains the property that either the children of a node are less than itself (max heap) or the children are greater than the node (min heap). Properties of Heap: Structural Property: This property states that it should be A Complete Binary Tree. For
4 min read
What's the relationship between "a" heap and "the" heap?
A Heap: "A Heap" refers to the heap data structure where we can store data in a specific order. Heap is a Tree-based data structure where the tree is a complete binary tree. Heap is basically of two types: Max-Heap: The key at the Root node of the tree will be the greatest among all the keys present in that heap and the same property will be follow
15+ min read
Why is Binary Heap Preferred over BST for Priority Queue?
A typical Priority Queue requires following operations to be efficient. Get Top Priority Element (Get minimum or maximum)Insert an elementRemove top priority elementDecrease Key A Binary Heap supports above operations with following time complexities: O(1)O(Logn)O(Logn)O(Logn) A Self Balancing Binary Search Tree like AVL Tree, Red-Black Tree, etc c
2 min read
Two nodes of a BST are swapped, correct the BST
Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST. Input: x = 20, y = 8 10 / \ 5 8 / \ 2 20Output: 10 / \ 5 20 / \ 2 8 Input: x = 10 y = 5 10 / \ 5 8 / \ 2 20Output: 5 / \ 10 20 / \ 2 8 Recommended ProblemFixing Two swapped nodes of a BSTSolve Problem Approach: The in-order traversal of a BST produces a sorted arr
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg