Name: __________________________ NetID: _____________ Name: __________________________ NetID: _____________ Name: __________________________ NetID: _____________
The tree shown below on the left has both the heap shape and the heap property.
Binary trees that are heaps are typically stored in an array. The root of the tree has index one (the array element with index zero isn't used). The children of the root are at indexes two (left child) and three (right child). In general, the children of the tree node with index k have indexes 2k (left child) and 2k+1 (right child).
The binary tree on the left below is stored in a vector as shown on the right.
| Conceptual Heap | Heap in array |
|---|---|
|
|
|
This process is shown below for adding the value 12 to the heap shown above.
First, the 12 is shown on the left added to maintain the heap shape. However, the 12 doesn't belong there (the heap property is violated) so the yellow node is shown on the right with no value, the newly added value 12 is "waiting" to find its place as all nodes on the path from the newly added leaf to the root are examined to find where the 12 belongs.
|
|
In the diagram above on the right, the 12 can't stay as a leaf, so the value in node above it is moved down to the leaf, and the yellow node conceptually moves up -- this is a new tentative spot for the 12 as shown on the left below.
|
|
The 12 cannot stay in the location shown above on the left since it is less than 15. The 15 is moved down to the yellow node, and the yellow node conceptually moves up -- this is the tentative spot for the 12 as shown above on the right.
The 12 belongs as the child of 7 (the root) since it is less than the root. The final tree is shown below. The newly-added 12 has been moved up from its original tentative location as a leaf (where the 21 is below) to its final location.