1 Binary heaps binary tree that satisfy two properties –structural property (is a complete tree) –heap-ordering property (minimum item on top) Can have maximizing heaps too.
2 Defining complete trees Perfect binary tree – all leaves are at the same depth height h 2 h+1 – 1 nodes 2 h – 1 non-leaves 2 h leaves
3 Defining complete trees (2) Complete trees, informally: A perfect binary tree of height h-1 with leaves added at height h in the leftmost positions. N-node complete tree of height h: h = log N 2 h N 2 h+1 - 1
4 Complete binary tree of height h For h = 0, just a single node. For h = 1, left child or two children. For h 2, either –the left subtree of the root is perfect with height h-1 and the right is complete with height h-1, OR –the left is complete with height h- 1 and the right is perfect with height h-2.
5 Heap Order Property Heap order property: For every non-root node X, the key in the parent of X is less than (or equal to) the key in X not a heap
6 Heap Operations findMin: addElement: bubble up. removeMin: replace root and bubble down
7 addElement: bubble up
8 removeMin: bubble down
9 buildHeap Build a heap from N items. Idea: put them into an array (in any order) and then “fix it up.” for (i = N/2; i > 0; i--) bubbleDown(i);
10 Representing Complete Binary Trees G ED CB A JKHI F L From node i, left child: right child: parent: ABCDEFGHIJKL implicit (array) implementation:
11 Why is it better? no pointers (space). *2, /2, + are faster operations than dereferencing a pointer. can get to parent easily Can we use the implicit representation for binary search trees?
12 Analysis of buildHeap An item that starts h nodes from a leaf moves down at most h nodes during its bubbling phase. Let S be the sum of the heights of all the nodes in a perfect binary tree. = h + 2(h-1) + 4(h-2) + … + 2 h-1 ·1 2S = 2h + 4(h-1) + … + 2 h-1 ·2 + 2 h ·1 S = – h … + 2 h h = 2 h+1 – 1 – (h+1) N
13 Heaps (summary) addElement: bubble up. O(log N) time. removeMin: bubble down. O(log N) time. buildHeap: for N items, O(N) time. Heapsort: –buildHeap on N items O(N) –N removeMin ops O(N log N)
14 Priority Queue ADT Checkout line at the supermarket Printer queues operations: addElement, removeMin addElementremoveMin
15 Simple implementations of the Priority Queue ADT insertdeleteMin (unsorted) list sorted list BST AVL tree (overkill?)
16 Other PQ Operations decreaseKey(p, ): bubble up increaseKey(p, ): bubble down remove(p): decreaseKey(p, ) deleteMin() Running time: O(log N) findMax: O(N).
17 d-heaps Same as binary heaps, except d children instead of 2. array implementation addElement: O(log d N) removee: O(d log d N) Why d-heaps?