Knowee
Questions
Features
Study Tools

Write a c++ program which can delete a value specified by the user. After deletion make sure the tree remains min heap. you cannot use vectors

Question

Write a C++ program which can delete a value specified by the user. After deletion make sure the tree remains min heap. You cannot use vectors.

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple C++ program that deletes a specified value from a min heap. This program uses arrays instead of vectors.

#include <iostream>
using namespace std;

void heapify(int arr[], int n, int i) {
    int smallest = i;
    int left = 2 * i + 1;
    int right = 2 * i + 2;

    if (left < n && arr[left] < arr[smallest])
        smallest = left;

    if (right < n && arr[right] < arr[smallest])
        smallest = right;

    if (smallest != i) {
        swap(arr[i], arr[smallest]);
        heapify(arr, n, smallest);
    }
}

void deleteRoot(int arr[], int& n) {
    int lastElement = arr[n - 1];
    arr[0] = lastElement;
    n = n - 1;
    heapify(arr, n, 0);
}

void printHeap(int arr[], int n) {
    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";
    cout << "\n";
}

int main() {
    int arr[] = {10, 5, 3, 2, 4};
    int n = sizeof(arr) / sizeof(arr[0]);

    cout << "Heap array : ";
    printHeap(arr, n);

    deleteRoot(arr, n);

    cout << "After deleting root: ";
    printHeap(arr, n);

    return 0;
}

This program first creates a min heap, then deletes the root (which is the smallest element in a min heap). After deletion, it heapifies the array to maintain the min heap property. Note that this program only deletes the root of the heap. If you want to delete a specific value from the heap, you would first need to find that value in the array, which could take O(n) time in the worst case.

This problem has been solved

Similar Questions

AVL tree is efficient for the followingAInsertionBAll the optionsCSearchingDDeletion

Write JAVA functions to implement DELETE_FIRST_NODE and TRAVERSEoperations in doubly linked lis

If we want to delete a node with two children in a BST, which node can replace it?

Which data structure is efficient to use for searching, insertion, deletion operationSelect one:a. Linked listO b. Arrayc. Treed. Graph

Which of the following is NOT a common binary tree operation?Group of answer choicesSearchInsertionSortingDeletion

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.