Binary Tree: Convert BST to Min Heap

Problem Statement:

Convert a BST into Min Heap.

Min Heap property:

All the values in the left sub tree of a node should be less than the value in the right subtree.

Example:

Input: 

    /*
     *           4
     *         /    \
     *        2      6
     *       / \    /  \
     *      1   3  5    7
     */

Output:

    /*
     *           1
     *         /    \
     *        2      5
     *       / \    /  \
     *      3   4  6    7
     */

Solution Explanation:

Take an temp array and insert node into the temp array in in-order traversal.

Then perform pre order traversal of the tree, copy the elements from the array into the tree node to get the result

Time Complexity: O(n)
Space Complexity: O(n)

Code Solution

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Node 
{
    int data;
    struct Node *left;
    struct Node *right;
};


struct Node* newNode(int data)
{
    struct Node* newNode = new Node;
    newNode->data = data;
    newNode->left = newNode->right = NULL;

    return (newNode);
}

void display_preorder(Node* root)
{
    if (root == NULL)
        return;

    cout << root->data << " ";
    display_preorder(root->left);
    display_preorder(root->right);
}


void insert_inorder(Node* root, vector<int>& nodes) 
{
    if (root == nullptr) 
    {
        return;
    }
  
    insert_inorder(root->left, nodes);  
    nodes.push_back(root->data);          
    insert_inorder(root->right, nodes); 
}

void insert_PreOrder(Node* root, vector<int>& nodes, int& index) 
{
    if (root == nullptr) 
    {
        return;
    }

    root->data = nodes[index++];

    insert_PreOrder(root->left, nodes, index);  
    insert_PreOrder(root->right, nodes, index);
}

void solution(Node* root) 
{
  
    vector<int> nodes;

    insert_inorder(root, nodes);

    int index = 0;

    insert_PreOrder(root, nodes, index);
}

int main(void)
{
    /*
     *           4
     *         /    \
     *        2      6
     *       / \    /  \
     *      1   3  5    7
     */
    struct Node* 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);

    solution(root);
    
    cout << "Preorder traversal : ";
    display_preorder(root);

    return 0;
}

Output

Preorder traversal : 1 2 3 4 5 6 7
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *