Heap
About
It is a Binary Tree where every child is:
Smaller than the current node. (
Max Heap)Larger than the current node. (
Min Heap)
Heap has a weak ordering, meaning that it is not totally ordered like a BST.
The order is only locally maintained, enough to satisfy the Heap conditions above.
Used in priority queues for example.
Node sequence of Heap
Nodes of the Heap follow a sequence to defines the first and last node of the Tree.
This sequence also helps on insertion and deletion, since inserted elements are added to the end (or last position), and deleted elements are deleted at position 0 (first position).
Inserting an element (Tree)
Elements are added at either:
The last level (height) where you have an empty space. (Usually from left to right)
New created level. (Usually from left to right)
Then check the added element against to see if it satisfy
Heapconditions.Repeat 2. until
Heapconditions are satisfied.
Deleting an element (Tree)
The top element is the one deleted.
Then the very last node in the Tree takes the place of the top node.
The node is checked against:
In a
MinHeap, the smallest of , then if they swapp positions.In a
MaxHeap, the highest of , then if they swapp positions.
Repeat 3. until
Heapconditions are satisfied.
Implementing Heap with Arrays
Heaps can easily be implemented with Arrays Data Structures, and thus facilitating the removal of nodes.
You simulate left and right childs and parent nodes in Arrays with the following formulas: (where i is the current node index being looked)
left child:right child:parent node:
Last updated