7
CISC 235 Topic 77 Binary Heaps A binary tree with an ordering property and a structural property Ordering Property: Min Heap –The element in the root is less than or equal to all elements in both its sub-trees –Both of its sub-trees are Min Heaps Ordering Property: Max Heap –The element in the root is greater than or equal to all elements in both its sub-trees –Both of its sub-trees are Max Heaps

8
CISC 235 Topic 78 Binary Heap Structural Property A binary heap is a binary tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right with no missing nodes.

12
CISC 235 Topic 712 Min Heap Operations: Insert 1.Find the next position at which to insert – after the “last” element in the heap – and create a “hole” at that postion 2.“Bubble” the hole up the tree by moving its parent element into it until the hole is at a position where the new element ≤ its children and ≥ its parent: the percolateUp() operation 3.Insert the new element in the hole

19
CISC 235 Topic 719 Min Heap Operations: ExtractMin 1.Copy the root (the minimum) to a temporary variable, thus creating a “hole” at the root. 2.Delete the last item in the heap by copying its element to a temporary location. 3.Find a place for that element by bubbling the hole down by moving its smallest child up until the element ≤ its children and ≥ its parent: the percolateDown() operation. 4.Place the former last element in that hole and return the former root.

29
CISC 235 Topic 729 Bottom-Up Heap Construction: BuildHeap If all the keys are given in advance and stored in an array, we can build a heap in worst-case O(n) time. Note: For simplicity, we’ll describe bottom-up heap construction for a full tree Algorithm: Call percolateDown() on nodes in non- heap tree in reverse level-order traversal to convert tree to a heap.

30
CISC 235 Topic 730 BuildHeap Algorithm 1.Build (n+1)/2 elementary heaps, with one key each, of the leaves of the tree (no work) 2.Build (n+1)/4 heaps, each with 3 keys, by joining pairs of elementary heaps with their parent as the root. Call percolateDown() 3.Build (n+1)/8 heaps, each with 7 keys, by joining pairs of 3-key heaps with their parent as the root. Call percolateDown() 4.Continue until reach root of entire tree.