Heap

A heap is a balanced binary tree that follows just two constraints:

  • The value in any node is less than the value in either of the children. This property is also called the heap property.
  • The tree is as balanced as possible—in the sense that any level is completely filled before a single node is inserted in the next level.

The following figure shows a sample heap:

Heap

Figure 1. A sample heap

It would not be really clear until we actually discuss how to insert elements and remove the least element. So let's jump into it.

Insertion

The first step of insertion is to insert the element in the next available position. The next available position is either ...

Get Java 9 Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.