SlideShare a Scribd company logo
1 of 25
David Luebke 1
CS 332: Algorithms
Go over exam
Binary Search Trees
David Luebke 2
Exam
● Hand back, go over exam
David Luebke 3
Review: Dynamic Sets
● Next few lectures will focus on data structures
rather than straight algorithms
● In particular, structures for dynamic sets
■ Elements have a key and satellite data
■ Dynamic sets support queries such as:
○ Search(S, k), Minimum(S), Maximum(S),
Successor(S, x), Predecessor(S, x)
■ They may also support modifying operations like:
○ Insert(S, x), Delete(S, x)
David Luebke 4
Review: Binary Search Trees
● Binary Search Trees (BSTs) are an important
data structure for dynamic sets
● In addition to satellite data, eleements have:
■ key: an identifying field inducing a total ordering
■ left: pointer to a left child (may be NULL)
■ right: pointer to a right child (may be NULL)
■ p: pointer to a parent node (NULL for root)
David Luebke 5
Review: Binary Search Trees
● BST property:
key[leftSubtree(x)] ≤ key[x] ≤ key[rightSubtree(x)]
● Example:
F
B H
KDA
David Luebke 6
Inorder Tree Walk
● What does the following code do?
TreeWalk(x)
TreeWalk(left[x]);
print(x);
TreeWalk(right[x]);
● A: prints elements in sorted (increasing) order
● This is called an inorder tree walk
■ Preorder tree walk: print root, then left, then right
■ Postorder tree walk: print left, then right, then root
David Luebke 7
Inorder Tree Walk
● Example:
● How long will a tree walk take?
● Prove that inorder walk prints in
monotonically increasing order
F
B H
KDA
David Luebke 8
Operations on BSTs: Search
● Given a key and a pointer to a node, returns an
element with that key or NULL:
TreeSearch(x, k)
if (x = NULL or k = key[x])
return x;
if (k < key[x])
return TreeSearch(left[x], k);
else
return TreeSearch(right[x], k);
David Luebke 9
BST Search: Example
● Search for D and C:
F
B H
KDA
David Luebke 10
Operations on BSTs: Search
● Here’s another function that does the same:
TreeSearch(x, k)
while (x != NULL and k != key[x])
if (k < key[x])
x = left[x];
else
x = right[x];
return x;
● Which of these two functions is more efficient?
David Luebke 11
Operations of BSTs: Insert
● Adds an element x to the tree so that the binary
search tree property continues to hold
● The basic algorithm
■ Like the search procedure above
■ Insert x in place of NULL
■ Use a “trailing pointer” to keep track of where you
came from (like inserting into singly linked list)
David Luebke 12
BST Insert: Example
● Example: Insert C
F
B H
KDA
C
David Luebke 13
BST Search/Insert: Running Time
● What is the running time of TreeSearch() or
TreeInsert()?
● A: O(h), where h = height of tree
● What is the height of a binary search tree?
● A: worst case: h = O(n) when tree is just a
linear string of left or right children
■ We’ll keep all analysis in terms of h for now
■ Later we’ll see how to maintain h = O(lg n)
David Luebke 14
Sorting With Binary Search Trees
● Informal code for sorting array A of length n:
BSTSort(A)
for i=1 to n
TreeInsert(A[i]);
InorderTreeWalk(root);
● Argue that this is Ω(n lg n)
● What will be the running time in the
■ Worst case?
■ Average case? (hint: remind you of anything?)
David Luebke 15
Sorting With BSTs
● Average case analysis
■ It’s a form of quicksort!
for i=1 to n
TreeInsert(A[i]);
InorderTreeWalk(root);
3 1 8 2 6 7 5
5 7
1 2 8 6 7 5
2 6 7 5
3
1 8
2 6
5 7
David Luebke 16
Sorting with BSTs
● Same partitions are done as with quicksort, but
in a different order
■ In previous example
○ Everything was compared to 3 once
○ Then those items < 3 were compared to 1 once
○ Etc.
■ Same comparisons as quicksort, different order!
○ Example: consider inserting 5
David Luebke 17
Sorting with BSTs
● Since run time is proportional to the number of
comparisons, same time as quicksort: O(n lg n)
● Which do you think is better, quicksort or
BSTsort? Why?
David Luebke 18
Sorting with BSTs
● Since run time is proportional to the number of
comparisons, same time as quicksort: O(n lg n)
● Which do you think is better, quicksort or
BSTSort? Why?
● A: quicksort
■ Better constants
■ Sorts in place
■ Doesn’t need to build data structure
David Luebke 19
More BST Operations
● BSTs are good for more than sorting. For
example, can implement a priority queue
● What operations must a priority queue have?
■ Insert
■ Minimum
■ Extract-Min
David Luebke 20
BST Operations: Minimum
● How can we implement a Minimum() query?
● What is the running time?
David Luebke 21
BST Operations: Successor
● For deletion, we will need a Successor()
operation
● Draw Fig 13.2
● What is the successor of node 3? Node 15?
Node 13?
● What are the general rules for finding the
successor of node x? (hint: two cases)
David Luebke 22
BST Operations: Successor
● Two cases:
■ x has a right subtree: successor is minimum node
in right subtree
■ x has no right subtree: successor is first ancestor of
x whose left child is also ancestor of x
○ Intuition: As long as you move to the left up the tree,
you’re visiting smaller nodes.
● Predecessor: similar algorithm
David Luebke 23
BST Operations: Delete
● Deletion is a bit tricky
● 3 cases:
■ x has no children:
○ Remove x
■ x has one child:
○ Splice out x
■ x has two children:
○ Swap x with successor
○ Perform case 1 or 2 to delete it
F
B H
KDA
C
Example: delete K
or H or B
David Luebke 24
BST Operations: Delete
● Why will case 2 always go to case 0 or case 1?
● A: because when x has 2 children, its
successor is the minimum in its right subtree
● Could we swap x with predecessor instead of
successor?
● A: yes. Would it be a good idea?
● A: might be good to alternate
David Luebke 25
The End
● Up next: guaranteeing a O(lg n) height tree

More Related Content

What's hot

Private and secure secret shared map reduce
Private and secure secret shared map reducePrivate and secure secret shared map reduce
Private and secure secret shared map reduceShantanu Sharma
 
Ee693 sept2014quizgt1
Ee693 sept2014quizgt1Ee693 sept2014quizgt1
Ee693 sept2014quizgt1Gopi Saiteja
 
Ee693 sept2014quizgt2
Ee693 sept2014quizgt2Ee693 sept2014quizgt2
Ee693 sept2014quizgt2Gopi Saiteja
 
CPM2013-tabei201306
CPM2013-tabei201306CPM2013-tabei201306
CPM2013-tabei201306Yasuo Tabei
 

What's hot (7)

Si math 107 ch5,8
Si math 107 ch5,8Si math 107 ch5,8
Si math 107 ch5,8
 
Private and secure secret shared map reduce
Private and secure secret shared map reducePrivate and secure secret shared map reduce
Private and secure secret shared map reduce
 
Ee693 sept2014quizgt1
Ee693 sept2014quizgt1Ee693 sept2014quizgt1
Ee693 sept2014quizgt1
 
Hash table
Hash tableHash table
Hash table
 
Day 3 examples
Day 3 examplesDay 3 examples
Day 3 examples
 
Ee693 sept2014quizgt2
Ee693 sept2014quizgt2Ee693 sept2014quizgt2
Ee693 sept2014quizgt2
 
CPM2013-tabei201306
CPM2013-tabei201306CPM2013-tabei201306
CPM2013-tabei201306
 

Viewers also liked

5.3 dyn algo-i
5.3 dyn algo-i5.3 dyn algo-i
5.3 dyn algo-iKrish_ver2
 
2.4 mst kruskal’s
2.4 mst  kruskal’s 2.4 mst  kruskal’s
2.4 mst kruskal’s Krish_ver2
 
1.9 b trees eg 03
1.9 b trees eg 031.9 b trees eg 03
1.9 b trees eg 03Krish_ver2
 
nhận thiết kế clip quảng cáo giá tốt
nhận thiết kế clip quảng cáo giá tốtnhận thiết kế clip quảng cáo giá tốt
nhận thiết kế clip quảng cáo giá tốtraul110
 
문제는 한글이 잘 구현되는가?
문제는 한글이 잘 구현되는가?문제는 한글이 잘 구현되는가?
문제는 한글이 잘 구현되는가?Choi Man Dream
 
5.2 divede and conquer 03
5.2 divede and conquer 035.2 divede and conquer 03
5.2 divede and conquer 03Krish_ver2
 
1.9 b trees 02
1.9 b trees 021.9 b trees 02
1.9 b trees 02Krish_ver2
 
2.4 mst prim &kruskal demo
2.4 mst  prim &kruskal demo2.4 mst  prim &kruskal demo
2.4 mst prim &kruskal demoKrish_ver2
 
CV Belinda Wahl 2015
CV Belinda Wahl 2015CV Belinda Wahl 2015
CV Belinda Wahl 2015Belinda Wahl
 
trabajo de cultural
trabajo de culturaltrabajo de cultural
trabajo de culturalargelures
 
5.4 randamized algorithm
5.4 randamized algorithm5.4 randamized algorithm
5.4 randamized algorithmKrish_ver2
 
평범한 이야기[Intro: 2015 의기제]
평범한 이야기[Intro: 2015 의기제]평범한 이야기[Intro: 2015 의기제]
평범한 이야기[Intro: 2015 의기제]대호 이
 

Viewers also liked (20)

4.1 webminig
4.1 webminig 4.1 webminig
4.1 webminig
 
РЕКЛАМНЫЕ МОДЕЛИ
РЕКЛАМНЫЕ МОДЕЛИРЕКЛАМНЫЕ МОДЕЛИ
РЕКЛАМНЫЕ МОДЕЛИ
 
5.3 dyn algo-i
5.3 dyn algo-i5.3 dyn algo-i
5.3 dyn algo-i
 
2.4 mst kruskal’s
2.4 mst  kruskal’s 2.4 mst  kruskal’s
2.4 mst kruskal’s
 
1.9 b trees eg 03
1.9 b trees eg 031.9 b trees eg 03
1.9 b trees eg 03
 
nhận thiết kế clip quảng cáo giá tốt
nhận thiết kế clip quảng cáo giá tốtnhận thiết kế clip quảng cáo giá tốt
nhận thiết kế clip quảng cáo giá tốt
 
Top Forex Brokers
Top Forex BrokersTop Forex Brokers
Top Forex Brokers
 
문제는 한글이 잘 구현되는가?
문제는 한글이 잘 구현되는가?문제는 한글이 잘 구현되는가?
문제는 한글이 잘 구현되는가?
 
5.2 divede and conquer 03
5.2 divede and conquer 035.2 divede and conquer 03
5.2 divede and conquer 03
 
1.9 b trees 02
1.9 b trees 021.9 b trees 02
1.9 b trees 02
 
2.4 mst prim &kruskal demo
2.4 mst  prim &kruskal demo2.4 mst  prim &kruskal demo
2.4 mst prim &kruskal demo
 
4.4 hashing02
4.4 hashing024.4 hashing02
4.4 hashing02
 
CV Belinda Wahl 2015
CV Belinda Wahl 2015CV Belinda Wahl 2015
CV Belinda Wahl 2015
 
trabajo de cultural
trabajo de culturaltrabajo de cultural
trabajo de cultural
 
Online Trading Concepts
Online Trading ConceptsOnline Trading Concepts
Online Trading Concepts
 
5.4 randamized algorithm
5.4 randamized algorithm5.4 randamized algorithm
5.4 randamized algorithm
 
RESUME-ARITRA BHOWMIK
RESUME-ARITRA BHOWMIKRESUME-ARITRA BHOWMIK
RESUME-ARITRA BHOWMIK
 
Salario minimo basico
Salario minimo basicoSalario minimo basico
Salario minimo basico
 
평범한 이야기[Intro: 2015 의기제]
평범한 이야기[Intro: 2015 의기제]평범한 이야기[Intro: 2015 의기제]
평범한 이야기[Intro: 2015 의기제]
 
4.2 bst 03
4.2 bst 034.2 bst 03
4.2 bst 03
 

Similar to 4.2 bst 02

Similar to 4.2 bst 02 (20)

lecture14.ppt
lecture14.pptlecture14.ppt
lecture14.ppt
 
5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx
 
Algorithms__Data_Structures_-_iCSC_2018.pptx
Algorithms__Data_Structures_-_iCSC_2018.pptxAlgorithms__Data_Structures_-_iCSC_2018.pptx
Algorithms__Data_Structures_-_iCSC_2018.pptx
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statistics
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
 
s11_bin_search_trees.ppt
s11_bin_search_trees.ppts11_bin_search_trees.ppt
s11_bin_search_trees.ppt
 
C12 bst
C12 bstC12 bst
C12 bst
 
C12 bst
C12 bstC12 bst
C12 bst
 
Lecture1-Architecture
Lecture1-ArchitectureLecture1-Architecture
Lecture1-Architecture
 
lecture1.ppt
lecture1.pptlecture1.ppt
lecture1.ppt
 
lecture7.ppt
lecture7.pptlecture7.ppt
lecture7.ppt
 
Randamization.pdf
Randamization.pdfRandamization.pdf
Randamization.pdf
 
b-tree.ppt
b-tree.pptb-tree.ppt
b-tree.ppt
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
session 15 hashing.pptx
session 15   hashing.pptxsession 15   hashing.pptx
session 15 hashing.pptx
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Splay Tree
Splay TreeSplay Tree
Splay Tree
 
Search algorithms master
Search algorithms masterSearch algorithms master
Search algorithms master
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Lec8
Lec8Lec8
Lec8
 

More from Krish_ver2

5.5 back tracking
5.5 back tracking5.5 back tracking
5.5 back trackingKrish_ver2
 
5.5 back track
5.5 back track5.5 back track
5.5 back trackKrish_ver2
 
5.5 back tracking 02
5.5 back tracking 025.5 back tracking 02
5.5 back tracking 02Krish_ver2
 
5.4 randomized datastructures
5.4 randomized datastructures5.4 randomized datastructures
5.4 randomized datastructuresKrish_ver2
 
5.4 randomized datastructures
5.4 randomized datastructures5.4 randomized datastructures
5.4 randomized datastructuresKrish_ver2
 
5.3 dynamic programming 03
5.3 dynamic programming 035.3 dynamic programming 03
5.3 dynamic programming 03Krish_ver2
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programmingKrish_ver2
 
5.2 divede and conquer 03
5.2 divede and conquer 035.2 divede and conquer 03
5.2 divede and conquer 03Krish_ver2
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquerKrish_ver2
 
5.1 greedyyy 02
5.1 greedyyy 025.1 greedyyy 02
5.1 greedyyy 02Krish_ver2
 
4.4 hashing ext
4.4 hashing  ext4.4 hashing  ext
4.4 hashing extKrish_ver2
 
4.4 external hashing
4.4 external hashing4.4 external hashing
4.4 external hashingKrish_ver2
 
4.1 sequentioal search
4.1 sequentioal search4.1 sequentioal search
4.1 sequentioal searchKrish_ver2
 
3.9 external sorting
3.9 external sorting3.9 external sorting
3.9 external sortingKrish_ver2
 
3.8 quick sort
3.8 quick sort3.8 quick sort
3.8 quick sortKrish_ver2
 

More from Krish_ver2 (20)

5.5 back tracking
5.5 back tracking5.5 back tracking
5.5 back tracking
 
5.5 back track
5.5 back track5.5 back track
5.5 back track
 
5.5 back tracking 02
5.5 back tracking 025.5 back tracking 02
5.5 back tracking 02
 
5.4 randomized datastructures
5.4 randomized datastructures5.4 randomized datastructures
5.4 randomized datastructures
 
5.4 randomized datastructures
5.4 randomized datastructures5.4 randomized datastructures
5.4 randomized datastructures
 
5.3 dynamic programming 03
5.3 dynamic programming 035.3 dynamic programming 03
5.3 dynamic programming 03
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programming
 
5.2 divede and conquer 03
5.2 divede and conquer 035.2 divede and conquer 03
5.2 divede and conquer 03
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquer
 
5.1 greedyyy 02
5.1 greedyyy 025.1 greedyyy 02
5.1 greedyyy 02
 
5.1 greedy
5.1 greedy5.1 greedy
5.1 greedy
 
5.1 greedy 03
5.1 greedy 035.1 greedy 03
5.1 greedy 03
 
4.4 hashing
4.4 hashing4.4 hashing
4.4 hashing
 
4.4 hashing ext
4.4 hashing  ext4.4 hashing  ext
4.4 hashing ext
 
4.4 external hashing
4.4 external hashing4.4 external hashing
4.4 external hashing
 
4.2 bst
4.2 bst4.2 bst
4.2 bst
 
4.1 sequentioal search
4.1 sequentioal search4.1 sequentioal search
4.1 sequentioal search
 
3.9 external sorting
3.9 external sorting3.9 external sorting
3.9 external sorting
 
3.8 quicksort
3.8 quicksort3.8 quicksort
3.8 quicksort
 
3.8 quick sort
3.8 quick sort3.8 quick sort
3.8 quick sort
 

Recently uploaded

Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
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 FellowsMebane Rash
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationNeilDeclaro1
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 

Recently uploaded (20)

Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
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
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 

4.2 bst 02

  • 1. David Luebke 1 CS 332: Algorithms Go over exam Binary Search Trees
  • 2. David Luebke 2 Exam ● Hand back, go over exam
  • 3. David Luebke 3 Review: Dynamic Sets ● Next few lectures will focus on data structures rather than straight algorithms ● In particular, structures for dynamic sets ■ Elements have a key and satellite data ■ Dynamic sets support queries such as: ○ Search(S, k), Minimum(S), Maximum(S), Successor(S, x), Predecessor(S, x) ■ They may also support modifying operations like: ○ Insert(S, x), Delete(S, x)
  • 4. David Luebke 4 Review: Binary Search Trees ● Binary Search Trees (BSTs) are an important data structure for dynamic sets ● In addition to satellite data, eleements have: ■ key: an identifying field inducing a total ordering ■ left: pointer to a left child (may be NULL) ■ right: pointer to a right child (may be NULL) ■ p: pointer to a parent node (NULL for root)
  • 5. David Luebke 5 Review: Binary Search Trees ● BST property: key[leftSubtree(x)] ≤ key[x] ≤ key[rightSubtree(x)] ● Example: F B H KDA
  • 6. David Luebke 6 Inorder Tree Walk ● What does the following code do? TreeWalk(x) TreeWalk(left[x]); print(x); TreeWalk(right[x]); ● A: prints elements in sorted (increasing) order ● This is called an inorder tree walk ■ Preorder tree walk: print root, then left, then right ■ Postorder tree walk: print left, then right, then root
  • 7. David Luebke 7 Inorder Tree Walk ● Example: ● How long will a tree walk take? ● Prove that inorder walk prints in monotonically increasing order F B H KDA
  • 8. David Luebke 8 Operations on BSTs: Search ● Given a key and a pointer to a node, returns an element with that key or NULL: TreeSearch(x, k) if (x = NULL or k = key[x]) return x; if (k < key[x]) return TreeSearch(left[x], k); else return TreeSearch(right[x], k);
  • 9. David Luebke 9 BST Search: Example ● Search for D and C: F B H KDA
  • 10. David Luebke 10 Operations on BSTs: Search ● Here’s another function that does the same: TreeSearch(x, k) while (x != NULL and k != key[x]) if (k < key[x]) x = left[x]; else x = right[x]; return x; ● Which of these two functions is more efficient?
  • 11. David Luebke 11 Operations of BSTs: Insert ● Adds an element x to the tree so that the binary search tree property continues to hold ● The basic algorithm ■ Like the search procedure above ■ Insert x in place of NULL ■ Use a “trailing pointer” to keep track of where you came from (like inserting into singly linked list)
  • 12. David Luebke 12 BST Insert: Example ● Example: Insert C F B H KDA C
  • 13. David Luebke 13 BST Search/Insert: Running Time ● What is the running time of TreeSearch() or TreeInsert()? ● A: O(h), where h = height of tree ● What is the height of a binary search tree? ● A: worst case: h = O(n) when tree is just a linear string of left or right children ■ We’ll keep all analysis in terms of h for now ■ Later we’ll see how to maintain h = O(lg n)
  • 14. David Luebke 14 Sorting With Binary Search Trees ● Informal code for sorting array A of length n: BSTSort(A) for i=1 to n TreeInsert(A[i]); InorderTreeWalk(root); ● Argue that this is Ω(n lg n) ● What will be the running time in the ■ Worst case? ■ Average case? (hint: remind you of anything?)
  • 15. David Luebke 15 Sorting With BSTs ● Average case analysis ■ It’s a form of quicksort! for i=1 to n TreeInsert(A[i]); InorderTreeWalk(root); 3 1 8 2 6 7 5 5 7 1 2 8 6 7 5 2 6 7 5 3 1 8 2 6 5 7
  • 16. David Luebke 16 Sorting with BSTs ● Same partitions are done as with quicksort, but in a different order ■ In previous example ○ Everything was compared to 3 once ○ Then those items < 3 were compared to 1 once ○ Etc. ■ Same comparisons as quicksort, different order! ○ Example: consider inserting 5
  • 17. David Luebke 17 Sorting with BSTs ● Since run time is proportional to the number of comparisons, same time as quicksort: O(n lg n) ● Which do you think is better, quicksort or BSTsort? Why?
  • 18. David Luebke 18 Sorting with BSTs ● Since run time is proportional to the number of comparisons, same time as quicksort: O(n lg n) ● Which do you think is better, quicksort or BSTSort? Why? ● A: quicksort ■ Better constants ■ Sorts in place ■ Doesn’t need to build data structure
  • 19. David Luebke 19 More BST Operations ● BSTs are good for more than sorting. For example, can implement a priority queue ● What operations must a priority queue have? ■ Insert ■ Minimum ■ Extract-Min
  • 20. David Luebke 20 BST Operations: Minimum ● How can we implement a Minimum() query? ● What is the running time?
  • 21. David Luebke 21 BST Operations: Successor ● For deletion, we will need a Successor() operation ● Draw Fig 13.2 ● What is the successor of node 3? Node 15? Node 13? ● What are the general rules for finding the successor of node x? (hint: two cases)
  • 22. David Luebke 22 BST Operations: Successor ● Two cases: ■ x has a right subtree: successor is minimum node in right subtree ■ x has no right subtree: successor is first ancestor of x whose left child is also ancestor of x ○ Intuition: As long as you move to the left up the tree, you’re visiting smaller nodes. ● Predecessor: similar algorithm
  • 23. David Luebke 23 BST Operations: Delete ● Deletion is a bit tricky ● 3 cases: ■ x has no children: ○ Remove x ■ x has one child: ○ Splice out x ■ x has two children: ○ Swap x with successor ○ Perform case 1 or 2 to delete it F B H KDA C Example: delete K or H or B
  • 24. David Luebke 24 BST Operations: Delete ● Why will case 2 always go to case 0 or case 1? ● A: because when x has 2 children, its successor is the minimum in its right subtree ● Could we swap x with predecessor instead of successor? ● A: yes. Would it be a good idea? ● A: might be good to alternate
  • 25. David Luebke 25 The End ● Up next: guaranteeing a O(lg n) height tree