In this document we review the important ideas behind
Binary trees can be efficiently stored in arrays by using an encoding that stores tree elements at particular indexes in the array. One can compute the indexes of that tree nodes left-child, right-child, and parent node using a simple formula.
We can envision this process by the following picture.
Trees as arrays with implicit links
Several invariants must hold for this to work.
The formulae for computing the tree child and parent relationships are:
root = 0
left_child i = i*2 + 1
right_child i = i*2 + 2
parent i | even i = (i `div` 2) - 1
| odd i = i `div` 2
A trace of adding a sequence of elements to an empty Max-heap. Note how the tree is always either a full or complete tree. Note how the last variable always points to the index of the last node of the tree.
empty heap add 3 3 0 1 2 3 4 5 6 index [3,-99,-99,-99,-99,-99,-99] values last = 0 add 6 +-6 3 0 1 2 3 4 5 6 index [6,3,-99,-99,-99,-99,-99] values last = 1 add 9 +-9-+ 3 6 0 1 2 3 4 5 6 index [9,3,6,-99,-99,-99,-99] values last = 2 add 7 +-9-+ +-7 6 3 0 1 2 3 4 5 6 index [9,7,6,3,-99,-99,-99] values last = 3 delete largest element +-7-+ 3 6 0 1 2 3 4 5 6 index [7,3,6,9,-99,-99,-99] values last = 2 add 8 +-8-+ +-7 6 3 0 1 2 3 4 5 6 index [8,7,6,3,-99,-99,-99] values last = 3 add 2 +---8-+ +-7-+ 6 3 2 0 1 2 3 4 5 6 index [8,7,6,3,2,-99,-99] values last = 4 add 56 +---56---+ +-7-+ +-8 3 2 6 0 1 2 3 4 5 6 index [56,7,8,3,2,6,-99] values last = 5 delete largest element +---8-+ +-7-+ 6 3 2 0 1 2 3 4 5 6 index [8,7,6,3,2,56,-99] values last = 4
A trace of adding a sequence of elements to an empty Min-heap. Note how the tree always maintains the leftist invariant.
add 5
5
add 8
+-5
8
add 3
+-3
+-5
8
add 9
+-3-+
+-5 9
8
add 4
+-3---+
+-5 +-4
8 9
add 2
+-----2
+-3---+
+-5 +-4
8 9
add 3
+-----2-+
+-3---+ 3
+-5 +-4
8 9
delete min element
+-3-----+
+-5 +-3
8 +-4
9
delete min element
+-3---+
+-4 +-5
9 8
delete min element
+-4---+
9 +-5
8
add 1
+-----1
+-4---+
9 +-5
8
add 4
+-----1-+
+-4---+ 4
9 +-5
8
delete min element
+-4-----+
9 +-4
+-5
8
Back to the Daily Record.