SlideShare une entreprise Scribd logo
1  sur  19
Array implementationof a balanced binary search tree
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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).
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
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
Done. Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2

Contenu connexe

Similaire à Balanced binary search tree on array

6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...
6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...
6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...
trangiaphuc362003181
 
Week09
Week09Week09
Week09
hccit
 
Basics in algorithms and data structure
Basics in algorithms and data structure Basics in algorithms and data structure
Basics in algorithms and data structure
Eman magdy
 

Similaire à Balanced binary search tree on array (20)

6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...
6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...
6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
 
2021 여름방학 정기 세미나 1주차
2021 여름방학 정기 세미나 1주차2021 여름방학 정기 세미나 1주차
2021 여름방학 정기 세미나 1주차
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptx
 
Lecture10
Lecture10Lecture10
Lecture10
 
UNIT V.docx
UNIT V.docxUNIT V.docx
UNIT V.docx
 
CipherKey Algorithm
CipherKey AlgorithmCipherKey Algorithm
CipherKey Algorithm
 
UNIT IV -Data Structures.pdf
UNIT IV -Data Structures.pdfUNIT IV -Data Structures.pdf
UNIT IV -Data Structures.pdf
 
Review session2
Review session2Review session2
Review session2
 
Binary Indexed Tree / Fenwick Tree
Binary Indexed Tree / Fenwick TreeBinary Indexed Tree / Fenwick Tree
Binary Indexed Tree / Fenwick Tree
 
python.pdf
python.pdfpython.pdf
python.pdf
 
Unit8 C
Unit8 CUnit8 C
Unit8 C
 
Week09
Week09Week09
Week09
 
CMT
CMTCMT
CMT
 
Technical aptitude questions_e_book1
Technical aptitude questions_e_book1Technical aptitude questions_e_book1
Technical aptitude questions_e_book1
 
Basics in algorithms and data structure
Basics in algorithms and data structure Basics in algorithms and data structure
Basics in algorithms and data structure
 
Buacm 3
Buacm 3Buacm 3
Buacm 3
 
L 17 ct1120
L 17 ct1120L 17 ct1120
L 17 ct1120
 
Using Topological Data Analysis on your BigData
Using Topological Data Analysis on your BigDataUsing Topological Data Analysis on your BigData
Using Topological Data Analysis on your BigData
 

Plus de Pier Giuliano Nioi (6)

Presentazione
PresentazionePresentazione
Presentazione
 
Eple thesis
Eple thesisEple thesis
Eple thesis
 
Implementazione hardware/software di un sistemamultitouch per l'interazione u...
Implementazione hardware/software di un sistemamultitouch per l'interazione u...Implementazione hardware/software di un sistemamultitouch per l'interazione u...
Implementazione hardware/software di un sistemamultitouch per l'interazione u...
 
Presentazione tesi multitouch
Presentazione tesi multitouch Presentazione tesi multitouch
Presentazione tesi multitouch
 
3d Graffiti 3d tag : a concept of augmented reality form mobile devices
3d Graffiti 3d tag : a concept of augmented reality form mobile devices3d Graffiti 3d tag : a concept of augmented reality form mobile devices
3d Graffiti 3d tag : a concept of augmented reality form mobile devices
 
Albero binario di ricerca bilanciato implementato su array - balanced bst on ...
Albero binario di ricerca bilanciato implementato su array - balanced bst on ...Albero binario di ricerca bilanciato implementato su array - balanced bst on ...
Albero binario di ricerca bilanciato implementato su array - balanced bst on ...
 

Dernier

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Dernier (20)

Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 

Balanced binary search tree on array

  • 1. Array implementationof a balanced binary search tree
  • 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