Data Structures and Analysis (COMP 410) David Stotts Computer Science Department UNC Chapel Hill
Representing Trees as Arrays
Array Rep for any BT Not heap structure (complete binary tree) 4 18 11 9 3 7 16 21 12 Not heap structure (complete binary tree) just a random binary tree 7 21 4 18 3 11 12 16 9 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Now get bigger… Add one node, double space needed in array 4 18 11 9 3 7 16 21 12 Add one node, double space needed in array 5 7 21 4 18 3 11 12 16 9 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 5 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
4 18 11 9 3 7 16 21 12 5 And bigger… 7 21 4 18 3 11 12 16 9 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 5 8 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 8 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
Array space used Some languages (without objects) would use huge space Array element is a static collection of data, each element might need 1000’s bytes array[10000] of struct { int, real, char[48] }
array int real chars int real chars 1 . . .
Array space used In Java (and languages with objects, pointers) can improve this Array element is an object, then each space in the array is a 8-byte address Each object is a collection of data, might be large, but we only need a object for each occupied array location class Element { int, real, char[48] } array[10000] of Element array[0] = new Element { 3, 4.5, “now is the time”} array[4] = new Element { 1, 6.3, “for all good code”}
. . . 3 4.5 “now is the time” 2 6.3 “for all good code” array 1 2 3 4 3 4.5 “now is the time” 1 2 3 4 5 6 7 2 6.3 “for all good code” . . .
Static layout, big space for each array element, used or not dynamic layout, each array element 64-bits, then big space for only elements used
Other problems… Add a node 8 3 and 16 have now changed levels When we add/move new nodes in a tree in the middle layers, we force rearrangement of values stored in the array Ex: 4 18 11 9 3 7 16 21 12 8 4 18 11 9 3 7 16 21 12 Add a node 8 between the 21 and 3 3 and 16 have now changed levels
Inner insert encoding the original tree 4 18 11 9 3 7 16 21 12 encoding the original tree 7 21 4 18 3 11 12 16 9 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Inner insert Add a node 8 between the 21 and 3 4 18 11 9 3 7 16 21 12 8 Add a node 8 between the 21 and 3 7 21 4 18 11 12 9 3 16 8 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Summary Array representation can be fast if the tree is built and then not changed (much) Changes in a tree require a lot of array element movement Array rep can be space inefficient if tree is not fairly full Array rep can be very space inefficient if array elements are static memory blocks rather than dynamically allocated objects
Beyond this is just templates END Beyond this is just templates