Heap Data Structure
Heap Data Structure
A heap is a (Almost complete Binary Tree- ACBT) tree where each parent node is
greater than or equal to its child nodes in a max-heap or less than or equal to its
child nodes in a min-heap. This means the largest or smallest value is always at the
top (root) of the tree.
There are two main types of heaps: Max-Heap and Min-Heap in data structure.
1. Max-Heap
In a max-heap, each parent node is greater than or equal to its child nodes. This
ensures that the largest value is always at the root of the tree.
MAX-HEAP
2. Min-Heap
In a min-heap, each parent node is less than or equal to its child nodes. This ensures that
the smallest value is always at the root of the tree.
MIN-HEAP
All levels are fully filled except possibly the last level.
This property ensures that the tree remains balanced, which is crucial for maintaining the
efficiency of heap operations.
. Heap Order Property
The heap must satisfy the heap order property, which differs for max-heaps and min-heaps:
Min-Heap Order Property: In a min-heap, each parent node is less than or equal to
its child nodes. This ensures that the smallest element is always at the root.
Heap Operations
Some of the important operations performed on a heap are described below
along with their algorithms.
Heapify
Heapify is the process of creating a heap data structure from a binary tree. It
is used to create a Min-Heap or a Max-Heap.
If there is no node,
create a newNode.
else (a node is already present)
insert the newNode at the end (last node from left to right.)
heapify the array
Insert
at the end
Select
the element to be deleted
2. Swap it with the last element.
Peek operation returns the maximum element from Max Heap or minimum
element from Min Heap without deleting the node.