Heaps are one type of data structure where elements are stored in two fashions either every parent element is greater than their children or is smaller than their children. Below we will discuss the two fashions.
Max-Heap
A max heap is a complete binary tree such that for each node, the key value in the node is greater than or equal to the value in its children. Observe that this implies that the root contains the largest value in the tree.
Min-Heap
A min-heap is a complete binary tree such that for each node, the key value in the node is smaller than or equal to the value in its children. Observe that this implies that the root contains the smallest value in the tree which is shown in the following Figure.
In either case of the above said two types of the heap the binary tree will grow in that way: parent(2*i),left-child(2*i+1), and right-child(2*i+2), where i ∈ [0,n]. When we insert or delete an element every time we have to maintain the heap property. Below we will give an example to clarify the insertion and deletion where the MAX-HEAP property is maintained which is clearly shown in the following figures. Suppose we have a complete binary tree which is shown below.
When we delete always the root element will be deleted and after that we have to maintain the heap property so that the rest of the elements are properly placed. Below we will see a clear picture of deletion.
Source Code of Max-Heap
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.