Introduction to Binary Heap and how to implement?

  1. It’s a complete 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.

  1. A Binary Heap is either Min Heap or Max Heap.

In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.

Things to Remember -

  • Arr[(i-1)/2] - Returns the parent node
  • Arr[(2*i)+1] - Returns the left child node
  • Arr[(2*i)+2] - Returns the right child node
class BHeap {
   private:
   vector <int> heap;
   int l(int parent);
   int r(int parent);
   int par(int child);
   void heapifyup(int index);
   void heapifydown(int index);
   public:
      BHeap() {}
      void Insert(int element);
      void DeleteMin();
      int ExtractMin();
      void showHeap();
      int Size();
};