SlideShare a Scribd company logo
1 of 28
CSC803
Data Structures &
Algorithm Analysis
Binary Search Trees
A Taxonomy of Trees
General Trees – any number of children / node
Binary Trees – max 2 children / node
Heaps – parent < (>) children
Binary Search Trees
Binary Trees
Binary search tree
Every element has a unique key.
The keys in a nonempty left subtree (right subtree)
are smaller (larger) than the key in the root of
subtree.
The left and right subtrees are also binary search
trees.
Binary Search Trees (BST) are a type of
Binary Trees with a special organization of
data.
This data organization leads to O(log n)
complexity for searches, insertions and
deletions in certain types of the BST
(balanced trees).
O(h) in general
Binary Search Trees
34 41 56 63 72 89 95
0 1 2 3 4 5 6
34 41 56
0 1 2
72 89 95
4 5 6
34 56
0 2
72 95
4 6
Binary Search algorithm of an array of sorted items
reduces the search space by one half after each comparison
Binary Search Algorithm
63
41 89
34 56
72 95
• the values in all nodes in the left subtree of a node are less than
the node value
• the values in all nodes in the right subtree of a node are greater
than the node values
Organization Rule for BST
Binary Tree
typedef struct tnode *ptnode;
typedef struct node {
short int key;
ptnode right, left;
} ;
sample binary search tree code
Searching in the BST
method search(key)
• implements the binary search based on comparison of the items
in the tree
• the items in the BST must be comparable (e.g integers, string,
etc.)
The search starts at the root. It probes down, comparing the
values in each node with the target, till it finds the first item equal
to the target. Returns this item or null if there is none.
BST Operations: Search
if the tree is empty
return NULL
else if the item in the node equals the target
return the node value
else if the item in the node is greater than the target
return the result of searching the left subtree
else if the item in the node is smaller than the target
return the result of searching the right subtree
Search in BST - Pseudocode
Search in a BST: C code
Ptnode search(ptnode root,
int key)
{
/* return a pointer to the node that
contains key. If there is no such
node, return NULL */
if (!root) return NULL;
if (key == root->key) return root;
if (key < root->key)
return search(root->left,key);
return search(root->right,key);
}
method insert(key)
 places a new item near the frontier of the BST while retaining its
organization of data:
starting at the root it probes down the tree till it finds a node
whose left or right pointer is empty and is a logical place for
the new value
uses a binary search to locate the insertion point
is based on comparisons of the new item and values of nodes
in the BST
Elements in nodes must be comparable!
BST Operations: Insertion
9
7
5
4 6 8
Case 1: The Tree is Empty
Set the root to a new node containing the item
Case 2: The Tree is Not Empty
Call a recursive helper method to insert the
item
10
10 > 7
10 > 9
10
if tree is empty
create a root node with the new key
else
compare key with the top node
if key = node key
replace the node with the new value
else if key > node key
compare key with the right subtree:
if subtree is empty create a leaf node
else add key in right subtree
else key < node key
compare key with the left subtree:
if the subtree is empty create a leaf node
else add key to the left subtree
Insertion in BST - Pseudocode
Insertion into a BST: C code
void insert (ptnode *node, int key)
{
ptnode ptr,
temp = search(*node, key);
if (temp || !(*node)) {
ptr = (ptnode) malloc(sizeof(tnode));
if (IS_FULL(ptr)) {
fprintf(stderr, “The memory is fulln”);
exit(1);
}
ptr->key = key;
ptr->left = ptr->right = NULL;
if (*node)
if (key<temp->key) temp->left=ptr;
else temp->right = ptr;
else *node = ptr;
}
}
 The order of supplying the data determines where it is
placed in the BST , which determines the shape of the BST
 Create BSTs from the same set of data presented each time
in a different order:
a) 17 4 14 19 15 7 9 3 16 10
b) 9 10 17 4 3 7 14 16 15 19
c) 19 17 16 15 14 10 9 7 4 3 can you guess this shape?
BST Shapes
 removes a specified item from the BST and adjusts the tree
 uses a binary search to locate the target item:
 starting at the root it probes down the tree till it finds the
target or reaches a leaf node (target not in the tree)
removal of a node must not leave a ‘gap’ in the tree,
BST Operations: Removal
method remove (key)
I if the tree is empty return false
II Attempt to locate the node containing the target using the
binary search algorithm
if the target is not found return false
else the target is found, so remove its node:
Case 1: if the node has 2 empty subtrees
replace the link in the parent with null
Case 2: if the node has a left and a right subtree
- replace the node's value with the max value in the
left subtree
- delete the max node in the left subtree
Removal in BST - Pseudocode
Case 3: if the node has no left child
- link the parent of the node
- to the right (non-empty) subtree
Case 4: if the node has no right child
- link the parent of the target
- to the left (non-empty) subtree
Removal in BST - Pseudocode
9
7
5
6
4 8 10
9
7
5
6 8 10
Case 1: removing a node with 2 EMPTY SUBTREES
parent
cursor
Removal in BST: Example
Removing 4
replace the link in the
parent with null
Case 2: removing a node with 2 SUBTREES
9
7
5
6 8 10
9
6
5
8 10
cursor
cursor
- replace the node's value with the max value in the left subtree
- delete the max node in the left subtree
4
4
Removing 7
Removal in BST: Example
What other element
can be used as
replacement?
9
7
5
6 8 10
9
7
5
6 8 10
cursor
cursor
parent
parent
the node has no left child:
link the parent of the node to the right (non-empty) subtree
Case 3: removing a node with 1 EMPTY SUBTREE
Removal in BST: Example
9
7
5
8 10
9
7
5
8 10
cursor
cursor
parent
parent
the node has no right child:
link the parent of the node to the left (non-empty) subtree
Case 4: removing a node with 1 EMPTY SUBTREE
Removing 5
4 4
Removal in BST: Example
The complexity of operations get, insert and
remove in BST is O(h) , where h is the height.
O(log n) when the tree is balanced. The updating
operations cause the tree to become unbalanced.
The tree can degenerate to a linear shape and the
operations will become O (n)
Analysis of BST Operations
BST tree = new BST();
tree.insert ("E");
tree.insert ("C");
tree.insert ("D");
tree.insert ("A");
tree.insert ("H");
tree.insert ("F");
tree.insert ("K");
>>>> Items in advantageous order:
K
H
F
E
D
C
A
Output:
Best Case
BST tree = new BST();
for (int i = 1; i <= 8; i++)
tree.insert (i);
>>>> Items in worst order:
8
7
6
5
4
3
2
1
Output:
Worst Case
tree = new BST ();
for (int i = 1; i <= 8; i++)
tree.insert(random());
>>>> Items in random order:
X
U
P
O
H
F
B
Output:
Random Case
Applications for BST
Sorting with binary search trees
Input: unsorted array
Output: sorted array
Algorithm ?
Running time ?
Prevent the degeneration of the BST :
A BST can be set up to maintain balance during
updating operations (insertions and removals)
Types of ST which maintain the optimal performance:
splay trees
AVL trees
2-4 Trees
Red-Black trees
B-trees
Better Search Trees

More Related Content

Similar to Lecture 7-BinarySearchTrees.ppt

Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docxsowmya koneru
 
THREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREETHREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREESiddhi Shrivas
 
Given a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfGiven a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfhadpadrrajeshh
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data StructureMeghaj Mallick
 
Python Spell Checker
Python Spell CheckerPython Spell Checker
Python Spell CheckerAmr Alarabi
 
Unit14_BinarySearchTree.ppt
Unit14_BinarySearchTree.pptUnit14_BinarySearchTree.ppt
Unit14_BinarySearchTree.pptplagcheck
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary treeZaid Shabbir
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil duttAnil Dutt
 
(a) There are three ways to traverse a binary tree pre-order, in-or.docx
(a) There are three ways to traverse a binary tree pre-order, in-or.docx(a) There are three ways to traverse a binary tree pre-order, in-or.docx
(a) There are three ways to traverse a binary tree pre-order, in-or.docxajoy21
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxdebishakespeare
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structureAnusruti Mitra
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptxskilljiolms
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structuresNiraj Agarwal
 
C programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdfC programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdfinfo309708
 
Binary trees
Binary treesBinary trees
Binary treesAmit Vats
 

Similar to Lecture 7-BinarySearchTrees.ppt (20)

Lab12 dsa bsee20075
Lab12 dsa bsee20075Lab12 dsa bsee20075
Lab12 dsa bsee20075
 
Binary tree
Binary treeBinary tree
Binary tree
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docx
 
THREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREETHREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREE
 
Given a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfGiven a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdf
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
 
Binary search trees (1)
Binary search trees (1)Binary search trees (1)
Binary search trees (1)
 
Data Structures
Data StructuresData Structures
Data Structures
 
L 19 ct1120
L 19 ct1120L 19 ct1120
L 19 ct1120
 
Python Spell Checker
Python Spell CheckerPython Spell Checker
Python Spell Checker
 
Unit14_BinarySearchTree.ppt
Unit14_BinarySearchTree.pptUnit14_BinarySearchTree.ppt
Unit14_BinarySearchTree.ppt
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary tree
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
 
(a) There are three ways to traverse a binary tree pre-order, in-or.docx
(a) There are three ways to traverse a binary tree pre-order, in-or.docx(a) There are three ways to traverse a binary tree pre-order, in-or.docx
(a) There are three ways to traverse a binary tree pre-order, in-or.docx
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docx
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptx
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
 
C programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdfC programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdf
 
Binary trees
Binary treesBinary trees
Binary trees
 

More from DrBashirMSaad

DS basics functions.ppt
DS basics functions.pptDS basics functions.ppt
DS basics functions.pptDrBashirMSaad
 
Algorithm analysis.pptx
Algorithm analysis.pptxAlgorithm analysis.pptx
Algorithm analysis.pptxDrBashirMSaad
 
Searching Informed Search.pdf
Searching Informed Search.pdfSearching Informed Search.pdf
Searching Informed Search.pdfDrBashirMSaad
 
procress and threads.ppt
procress and threads.pptprocress and threads.ppt
procress and threads.pptDrBashirMSaad
 
2.02.Data_structures_and_algorithms (1).pptx
2.02.Data_structures_and_algorithms (1).pptx2.02.Data_structures_and_algorithms (1).pptx
2.02.Data_structures_and_algorithms (1).pptxDrBashirMSaad
 
1b-150720094704-lva1-app6892.pdf
1b-150720094704-lva1-app6892.pdf1b-150720094704-lva1-app6892.pdf
1b-150720094704-lva1-app6892.pdfDrBashirMSaad
 
lec06-programming.ppt
lec06-programming.pptlec06-programming.ppt
lec06-programming.pptDrBashirMSaad
 
Matlab_Simulink_Tutorial.ppt
Matlab_Simulink_Tutorial.pptMatlab_Simulink_Tutorial.ppt
Matlab_Simulink_Tutorial.pptDrBashirMSaad
 

More from DrBashirMSaad (11)

DS basics functions.ppt
DS basics functions.pptDS basics functions.ppt
DS basics functions.ppt
 
Algorithm analysis.pptx
Algorithm analysis.pptxAlgorithm analysis.pptx
Algorithm analysis.pptx
 
Searching Informed Search.pdf
Searching Informed Search.pdfSearching Informed Search.pdf
Searching Informed Search.pdf
 
procress and threads.ppt
procress and threads.pptprocress and threads.ppt
procress and threads.ppt
 
2.02.Data_structures_and_algorithms (1).pptx
2.02.Data_structures_and_algorithms (1).pptx2.02.Data_structures_and_algorithms (1).pptx
2.02.Data_structures_and_algorithms (1).pptx
 
1b-150720094704-lva1-app6892.pdf
1b-150720094704-lva1-app6892.pdf1b-150720094704-lva1-app6892.pdf
1b-150720094704-lva1-app6892.pdf
 
01_intro-cpp.ppt
01_intro-cpp.ppt01_intro-cpp.ppt
01_intro-cpp.ppt
 
lec06-programming.ppt
lec06-programming.pptlec06-programming.ppt
lec06-programming.ppt
 
CS351-L1.ppt
CS351-L1.pptCS351-L1.ppt
CS351-L1.ppt
 
Matlab_Simulink_Tutorial.ppt
Matlab_Simulink_Tutorial.pptMatlab_Simulink_Tutorial.ppt
Matlab_Simulink_Tutorial.ppt
 
002 AWSSlides.pdf
002 AWSSlides.pdf002 AWSSlides.pdf
002 AWSSlides.pdf
 

Recently uploaded

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 

Recently uploaded (20)

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

Lecture 7-BinarySearchTrees.ppt

  • 1. CSC803 Data Structures & Algorithm Analysis Binary Search Trees
  • 2. A Taxonomy of Trees General Trees – any number of children / node Binary Trees – max 2 children / node Heaps – parent < (>) children Binary Search Trees
  • 3. Binary Trees Binary search tree Every element has a unique key. The keys in a nonempty left subtree (right subtree) are smaller (larger) than the key in the root of subtree. The left and right subtrees are also binary search trees.
  • 4. Binary Search Trees (BST) are a type of Binary Trees with a special organization of data. This data organization leads to O(log n) complexity for searches, insertions and deletions in certain types of the BST (balanced trees). O(h) in general Binary Search Trees
  • 5. 34 41 56 63 72 89 95 0 1 2 3 4 5 6 34 41 56 0 1 2 72 89 95 4 5 6 34 56 0 2 72 95 4 6 Binary Search algorithm of an array of sorted items reduces the search space by one half after each comparison Binary Search Algorithm
  • 6. 63 41 89 34 56 72 95 • the values in all nodes in the left subtree of a node are less than the node value • the values in all nodes in the right subtree of a node are greater than the node values Organization Rule for BST
  • 7. Binary Tree typedef struct tnode *ptnode; typedef struct node { short int key; ptnode right, left; } ; sample binary search tree code
  • 8. Searching in the BST method search(key) • implements the binary search based on comparison of the items in the tree • the items in the BST must be comparable (e.g integers, string, etc.) The search starts at the root. It probes down, comparing the values in each node with the target, till it finds the first item equal to the target. Returns this item or null if there is none. BST Operations: Search
  • 9. if the tree is empty return NULL else if the item in the node equals the target return the node value else if the item in the node is greater than the target return the result of searching the left subtree else if the item in the node is smaller than the target return the result of searching the right subtree Search in BST - Pseudocode
  • 10. Search in a BST: C code Ptnode search(ptnode root, int key) { /* return a pointer to the node that contains key. If there is no such node, return NULL */ if (!root) return NULL; if (key == root->key) return root; if (key < root->key) return search(root->left,key); return search(root->right,key); }
  • 11. method insert(key)  places a new item near the frontier of the BST while retaining its organization of data: starting at the root it probes down the tree till it finds a node whose left or right pointer is empty and is a logical place for the new value uses a binary search to locate the insertion point is based on comparisons of the new item and values of nodes in the BST Elements in nodes must be comparable! BST Operations: Insertion
  • 12. 9 7 5 4 6 8 Case 1: The Tree is Empty Set the root to a new node containing the item Case 2: The Tree is Not Empty Call a recursive helper method to insert the item 10 10 > 7 10 > 9 10
  • 13. if tree is empty create a root node with the new key else compare key with the top node if key = node key replace the node with the new value else if key > node key compare key with the right subtree: if subtree is empty create a leaf node else add key in right subtree else key < node key compare key with the left subtree: if the subtree is empty create a leaf node else add key to the left subtree Insertion in BST - Pseudocode
  • 14. Insertion into a BST: C code void insert (ptnode *node, int key) { ptnode ptr, temp = search(*node, key); if (temp || !(*node)) { ptr = (ptnode) malloc(sizeof(tnode)); if (IS_FULL(ptr)) { fprintf(stderr, “The memory is fulln”); exit(1); } ptr->key = key; ptr->left = ptr->right = NULL; if (*node) if (key<temp->key) temp->left=ptr; else temp->right = ptr; else *node = ptr; } }
  • 15.  The order of supplying the data determines where it is placed in the BST , which determines the shape of the BST  Create BSTs from the same set of data presented each time in a different order: a) 17 4 14 19 15 7 9 3 16 10 b) 9 10 17 4 3 7 14 16 15 19 c) 19 17 16 15 14 10 9 7 4 3 can you guess this shape? BST Shapes
  • 16.  removes a specified item from the BST and adjusts the tree  uses a binary search to locate the target item:  starting at the root it probes down the tree till it finds the target or reaches a leaf node (target not in the tree) removal of a node must not leave a ‘gap’ in the tree, BST Operations: Removal
  • 17. method remove (key) I if the tree is empty return false II Attempt to locate the node containing the target using the binary search algorithm if the target is not found return false else the target is found, so remove its node: Case 1: if the node has 2 empty subtrees replace the link in the parent with null Case 2: if the node has a left and a right subtree - replace the node's value with the max value in the left subtree - delete the max node in the left subtree Removal in BST - Pseudocode
  • 18. Case 3: if the node has no left child - link the parent of the node - to the right (non-empty) subtree Case 4: if the node has no right child - link the parent of the target - to the left (non-empty) subtree Removal in BST - Pseudocode
  • 19. 9 7 5 6 4 8 10 9 7 5 6 8 10 Case 1: removing a node with 2 EMPTY SUBTREES parent cursor Removal in BST: Example Removing 4 replace the link in the parent with null
  • 20. Case 2: removing a node with 2 SUBTREES 9 7 5 6 8 10 9 6 5 8 10 cursor cursor - replace the node's value with the max value in the left subtree - delete the max node in the left subtree 4 4 Removing 7 Removal in BST: Example What other element can be used as replacement?
  • 21. 9 7 5 6 8 10 9 7 5 6 8 10 cursor cursor parent parent the node has no left child: link the parent of the node to the right (non-empty) subtree Case 3: removing a node with 1 EMPTY SUBTREE Removal in BST: Example
  • 22. 9 7 5 8 10 9 7 5 8 10 cursor cursor parent parent the node has no right child: link the parent of the node to the left (non-empty) subtree Case 4: removing a node with 1 EMPTY SUBTREE Removing 5 4 4 Removal in BST: Example
  • 23. The complexity of operations get, insert and remove in BST is O(h) , where h is the height. O(log n) when the tree is balanced. The updating operations cause the tree to become unbalanced. The tree can degenerate to a linear shape and the operations will become O (n) Analysis of BST Operations
  • 24. BST tree = new BST(); tree.insert ("E"); tree.insert ("C"); tree.insert ("D"); tree.insert ("A"); tree.insert ("H"); tree.insert ("F"); tree.insert ("K"); >>>> Items in advantageous order: K H F E D C A Output: Best Case
  • 25. BST tree = new BST(); for (int i = 1; i <= 8; i++) tree.insert (i); >>>> Items in worst order: 8 7 6 5 4 3 2 1 Output: Worst Case
  • 26. tree = new BST (); for (int i = 1; i <= 8; i++) tree.insert(random()); >>>> Items in random order: X U P O H F B Output: Random Case
  • 27. Applications for BST Sorting with binary search trees Input: unsorted array Output: sorted array Algorithm ? Running time ?
  • 28. Prevent the degeneration of the BST : A BST can be set up to maintain balance during updating operations (insertions and removals) Types of ST which maintain the optimal performance: splay trees AVL trees 2-4 Trees Red-Black trees B-trees Better Search Trees