Array representation of Binary Trees ==================================== 1 2 3 4 5 6 7 8 9 Array format: Node, Left, Right Not achievable Array format: Row Order { 1 2 3 4 5 6 7 8 9} 0 1 2 3 4 5 6 7 8 +--+--+--+--+--+--+--+--+--+- | 1| 2| 3| 4| 5| 6| 7| 8| 9| +--+--+--+--+--+--+--+--+--+- Left(0) is at 1 Right(0) is at 2 Left(1) 3 Right(1) 4 Left(2) 5 Right(2) 6 Left(3) 7 Right(3) 8 Index | Left | Right -------+------+------ 0 | 1 | 2 1 | 3 | 4 2 | 5 | 6 3 | 7 | 8 LEFT(i) = 2i + 1 RIGHT(i) = 2i + 2 PARENT(i) = (i -1) / 2 Drawbacks - Can't grow the tree - Can't represent sparse trees - represent empty nodes * sentinel value * parallel array of booleans Good for - Quick and dirty trees - Serializing trees (store in a file) - Data structure/tree format which ensures that the tree can be filled from left to right. (for example, heaps) Heaps ===== A tree structure where every node obeys a heap property. Example Properties - MIN Heap property. The root of every tree is the minimal value in that tree. All nodes below the root have a larger key value. 1 2 3 4 5 6 7 - MAX Heap Property The root node is the largest node value in that tree. All nodes below the root have a smaller key value 7 5 6 3 4 2 1 Uses - Priority Queue MIN HEAP Find the smallest item in constant time MAX HEAP Find the biggest item in constant time MIN MAX HEAP Find the biggest and the smallest in constant time - Sorting (Heap Sort) O(n lg n) - Resource Allocation Basic Operations heapify(ar, i) - adjust ar[i] so that it conforms to the heap property buildHeap(ar, n) - reorders ar so that it is is in heap order Heap Representations Binary Heap: Binary Tree Fibonocci Heap: Very efficient but more difficult.