Basic binary tree facts:
Here is a full binary tree (tilt your head 90 degrees to the left):
1
2
3
root 7
4
5
6
Here is a complete binary tree (that is not full):
2
3
root 7
4
5
6
|
|
Also, given the position of a child node, the position of the parent node can be found as:
|
Here this is integer division, meaning that the remainder is thrown away after division. The result of the division has no decimal fraction.
A heap is a complete binary tree such that the value in every parent node is at least as large as the values in the child nodes.
Here is a heap:
3
2
root 7
4
6
5
For example, in the tree above, adding, say, 10 to the heap gives:
10
2
3
root 7
4
5
6
To do this ``reheapify upwards'' as follows:
Now the tree looks like this:
2
7
3
root 10
4
5
6
The tree is again a heap.
If the parent is smaller, exchange.
Set i to the location of the parent.
The trick is to restore the heap nature of the tree (all parents are at least as large as their children) after removing the root. The process is:
For example in this tree:
1
7
6
10
4
5
2
the replacement will give:
7
6
1
4
5
2
To make the tree a heap again, ``reheapify downwards'' as follows:
The result is:
6
1
7
4
5
2
which is a heap again.
If one of these last two values is larger than the value at i, then
Heaps can be used to perform a quite efficient sort. Here is how it works, given an array A: