Heap (data structure)

A heap is a special tree-based data structure. It is based on a complete tree, and satisfies the following heap properties:
 * Min-heap: In a min-heap, every single node is smaller than all of its descendants.
 * Max-heap: In a max-heap, every single node is greater than all of its descendants.

Binary heap


A binary heap is a complete binary tree that satisfies the heap properties.

A binary heap is either a min-heap or a max-heap.

Representation of a binary heap as an array
Since a binary heap is a complete binary tree, i.e. it is a balanced binary tree with all non-empty nodes generated on the left as much as possible, it can be represented as an array in memory:
 * The root of the heap is the first element, i.e. index 0, of the array.
 * For each node of index  in the array:
 * Its parent node index is  .
 * Its left child index is  .
 * Its right child index is  .

The traversal order to list all nodes in an array is called "level-order traversal".

Check if a binary tree is a min-heap
Here is the method to check if a binary tree is a min-heap.

We need to do two steps:
 * 1) Check if the binary tree is complete.
 * 2) Check if heap property is satisfied recursively for every node.

Time complexity
So total time complexity is O(n).
 * 1) Going over the entire binary tree to check completeness takes O(n) time.
 * 2) Checking heap property for each node recursively also takes O(n) time.

Space complexity

 * Stack
 * 1) In the process of checking completeness of the binary tree, the space complexity is O(1).
 * 2) In recursively checking heap property, since a complete binary tree has O(log n) height, the space complexity is O(log n).


 * Heap
 * 1) In checking completeness of the binary tree, we have created a BFS queue that may receive a maximum of (n/2) nodes (for a perfect binary tree). So the space complexity is O(n).
 * 2) In checking heap property, we have not allocated any new objects. So the space complexity is O(1).

So the total space complexity is O(n).

Sample problems

 * K-th smallest/largest element in unsorted array
 * K-th smallest number in sorted matrix