2. Given a set oforderedelements, weaskourselvesifitispossibletobuild a binarysearchtreeupontheseelements in a sequential data structurelikeanarray; the answer, ofcourse, is yes. And in a bottom-up way. Theserepresentationdoesnotmakeuseofpointers, typical in a linkedrepresentationof a binarysearchtree, thereforeyousaveO(2n) memorylocations. Our BST willsave the orderedelementsonly at leafnodes, and internalnodeswillbevalorizedwithkey-valuesthatwill guide everysearchoperation. Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
3. Given the set containing5 elements, the balancedbinarysearchtreeoftheseelementsusuallyisrepresented in a ‘linked’ way likethis: 3 2 4 1 3 4 5 1 2 Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
4. 3 lvl 0 Treeismadeof 3 levels (withroot at level 0) Ithas5 ‘leaves’ and 4 ‘nodes’ Formally, ifnis the numberof elements, wewillhavenleaves and n-1 internalnodes Itis a complete and balancedtree The numberofleavesisbetween2i e 2i+1, wherei and i+1 are the levelswhere the leaves are stored In this case wehave22< 5 < 23, 4 < 5 < 8 2 4 lvl 1 1 lvl 2 3 4 5 1 2 Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 lvl 3
5. Torepresentthattreeweuse the samerepresentationusedfor a similar data structure, usuallycalledheap(maxo min) A node at position i on anarray, willhavehisleftchild at position 2*i and his right child at position 2*i +1, and everychildnode in the arraywillhavehisownfather at position floor(i/2) Ourbinarytree on arraywillhave(n-1)+n+1 memorylocations, (internalnodes)+ leaves+1 Final+1isabout the optiontoleaveempty the first location of the array 3 2 4 1 3 4 5 1 2 Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
6. Ifwealreadyhave a linkedrepresentationof the treebased on oursortedelements, itis possibile to transfer it in a arrayrepresentationsimplytraversing the levelsof the tree, keeping in mind previousformulasaboutchild and fatherspositions. Likethis the roothas position 1 and hischildren and are stored at2*1=2 and 2*1+1=3 . Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 1 3 4 5 1 2 3 3 4 2 2 4 1 3 4 5 1 2
7. Buthow do webuildthistree in a bottom-up way ifwe don’t have the linkedrepresentationof the tree, butonlyourelementssorted(usualli in a ascendingorder) ? Wedefinitelymust produce the sameresultof a treetraversingbylevels, seenbefore, so weneed the same number of memory locations like the array resulting the ‘transformation’ It is quite simple but we must note that our input array, with our elements, is in the final array but in a ‘strange’ way. Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
8. Note the elements(1 2 3 4 5) order: The leaves(redones), aresstored in a ascendingorderbut, let’s say, in a ‘broken’ sequence, 3 4 5 1 2 insteadof 1 2 3 4 5 Thisis the directconsequenceof the treelevels Wemustfind out whatelementsfromour input arraywemustmove in anotherpositions Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 1 3 4 5 1 2
9. Weuse the basictheoryofbinarytrees and it’s link with the powerof the number 2 anwewilluse the toollog2(log base 2) Wesaidthatleaves are storedbetween the level 2i and 2i+1”,, they are practically spread at most in twodifferentand sequentiallevels, i and i+1 Wehavetofind out whatvaluesofourelementmusto go at level i and the otherseventuallywill go on the next level, i+1 Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
10. In ourexamplewehavethat 22< 5 < 23 , 4 < 5 < 8 In thisimagewe note thatonly ONE nodeoflevel i ( in this case i=2) is a internalnodeoflevel i ( the other are onlyleaves in red) and thisnodebringstwoleaves in the level i+1 Wehavetofindthesnodes, thatbringscertainelementstobe on level i+1: ifwesubtract 4 from 5, weobrain the numberofnodethatwe are lookingfor, in this case 1 nodethatbrings 2 elementstobeleaves in level i+1 Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 1 3 4 5 1 2
11. This 2 ( is the resultof 1*2, [numer_of_node_we_were_looking_for]*2 ), represent the numberofelementtomovefrom head to the tailofour input vector Doingthisweobtain the right orderwewerelookingfor, like in the level-traversalrepresentationshownbefore. Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 1 3 4 5 1 2
12. Firtswemustunderstandhowtoobtainthat4 ofourexamplewithoutanyknowledgeabout the numberoflevelthere are in our future tree It’s timetouse some mathematics : log2 WE onlyknow the numberofelementsthatwillbeourleaves, in the example are 5 (formallyn) Using log andfloor() wefound the valuethatwe are lookingforof the level i. Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
13. log2 5 = 2.3219... floor(log2 5) = 2 Nowwehave the numberofleveli Toknowhowmanynodes are usuallystored at level i in a full tree, eweusepowersof 2 nodeNumber=2floor(log2 n) = 2floor(log2 5) = 22 = 4 And therewehaveour 4! Therefore ,5 – 4 =1 and 1*2= 2; wemustmove 2 elementsfrom head totail Let’s now complete our BST Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
14. Let’s create anarrayoflenght (internalnodes)+(leaves)+1, in our case 10 ( 4 + 5 +1) , and weourvectorwithmovedelements Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
15. Foreveryfre location, from bottom to top, wemustchoose the key-valuetolead the search Ifcurrentnodehasn’t ‘nephews’ we take the valueofhisleftchild Otherwisewe look for the last ‘nephew’ on the right from the leftchild Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
16. Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 Index 4, hasonlychildren take the leftvalue(2*i) Alsoforindex 3(at position 6 = 2*i, i=3).
17. Index 2, has ‘nephews’, we take the last right on of the leftchildofnode Alsofor position 1, root Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
18. Wehavefinallybuilt the balancedbinarysearchtree, savingtime and memorywith the useof 2 formulasforsearching Youmaywanttocheckifyou are already or you are goingtofind a value out ofbounds, topreventeruntimeerrors Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 3 2 4 1 3 4 5 1 2 1 3 4 5 1 2
19. Done. Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2