SlideShare a Scribd company logo
Binary Trees,Binary Search Trees
TreesLinear access time of linked lists is prohibitiveDoes there exist any simple data structure for which the running time of most operations (search, insert, delete) is O(log N)?
TreesA tree is a collection of nodesThe collection can be empty(recursive definition) If not empty, a tree consists of a distinguished node r (the root), and zero or more nonempty subtrees T1, T2, ...., Tk, each of whose roots are connected by a directed edge from r
Some TerminologiesChild and parentEvery node except the root has one parent A node can have an arbitrary number of childrenLeavesNodes with no children Siblingnodes with same parent
Some TerminologiesPathLengthnumber of edges on the pathDepthof a nodelength of the unique path from the root to that nodeThe depth of a tree is equal to the depth of the deepest leafHeight of a nodelength of the longest path from that node to a leafall leaves are at height 0The height of a tree is equal to the height of the rootAncestor and descendantProper ancestor and proper descendant
Example: UNIX Directory
Binary TreesA tree in which no node can have more than two childrenThe depth of an “average” binary tree is considerably smaller than N, eventhough in the worst case, the depth can be as large as N – 1.
Example: Expression TreesLeaves are operands (constants or variables)The other nodes (internal nodes) contain operatorsWill not be a binary tree if some operators are not binary
Tree traversalUsed to print out the data in a tree in a certain orderPre-order traversalPrint the data at the rootRecursively print out all data in the left subtreeRecursively print out all data in the right subtree
Preorder, Postorder and InorderPreorder traversalnode, left, rightprefix expression++a*bc*+*defg
Preorder, Postorder and InorderPostorder traversalleft, right, nodepostfix expressionabc*+de*f+g*+Inorder traversalleft, node, right.infix expressiona+b*c+d*e+f*g
Preorder
Postorder
Preorder, Postorder and Inorder
Binary TreesPossible operations on the Binary Tree ADTparentleft_child, right_childsiblingroot, etcImplementationBecause a binary tree has at most two children, we can keep direct pointers to them
compare: Implementation of a general tree
Binary Search TreesStores keys in the nodes in a way so that searching, insertion and deletion can be done efficiently.Binary search tree propertyFor every node X, all the keys in its left subtree are smaller than the key value in X, and all the keys in its right subtree are larger than the key value in X
Binary Search TreesA binary search treeNot a binary search tree
Binary search treesAverage depth of a node is O(log N); maximum depth of a node is O(N)Two binary search trees representing the same set:
Implementation
Searching BSTIf we are searching for 15, then we are done.If we are searching for a key < 15, then we should search in the left subtree.If we are searching for a key > 15, then we should search in the right subtree.
Binary trees1
Searching (Find)Find X: return a pointer to the node that has key X, or NULL if there is no such nodeTime complexityO(height of the tree)
Inorder traversal of BSTPrint out all the keys in sorted orderInorder: 2, 3, 4, 6, 7, 9, 13, 15, 17, 18, 20
findMin/ findMaxReturn the node containing the smallest element in the treeStart at the root and go left as long as there is a left child. The stopping point is the smallest elementSimilarly for findMaxTime complexity = O(height of the tree)
insertProceed down the tree as you would with a findIf X is found, do nothing (or update something)Otherwise, insert X at the last spot on the path traversedTime complexity = O(height of the tree)
deleteWhen we delete a node, we need to consider how we take care of the children of the deleted node.This has to be done such that the property of the search tree is maintained.
deleteThree cases:(1) the node is a leafDelete it immediately(2) the node has one childAdjust a pointer from the parent to bypass that node
delete(3) the node has 2 childrenreplace the key of that node with the minimum element at the right subtree delete the minimum element Has either no child or only right child because if it has a left child, that left child would be smaller and would have been chosen. So invoke case 1 or 2.Time complexity = O(height of the tree)
AVL-Trees
Balanced binary treeThe disadvantage of a binary search tree is that its height can be as large as N-1This means that the time needed to perform insertion and deletion and many other operations can be O(N) in the worst caseWe want a tree with small heightA binary tree with N node has height at least(log N) Thus, our goal is to keep the height of a binary search tree O(log N)Such trees are called balanced binary search trees.  Examples are AVL tree, red-black tree.
AVL treeHeight of a nodeThe height of a leaf is 1.  The height of a null pointer is zero.The height of an internal node is the maximum height of its children plus 1Note that this definition of height is different from the one we defined previously (we defined the height of a leaf as zero previously).
AVL treeAn AVL tree is a binary search tree in whichfor every node in the tree, the height of the left and right subtrees differ by at most 1.AVL property violated here
AVL treeLet x be the root of an AVL tree of height hLet Nh denote the minimum number of nodes in an AVL tree of height hClearly, Ni≥ Ni-1 by definitionWe haveBy repeated substitution, we obtain the general formThe boundary conditions are: N1=1 and N2 =2. This implies that h = O(log Nh).Thus, many operations (searching, insertion, deletion) on an AVL tree will take O(log N) time.
RotationsWhen the tree structure changes (e.g., insertion or deletion), we need to transform the tree to restore the AVL tree property.This is done using single rotations or double rotations.yxACBe.g. Single RotationxyCBAAfter RotationBefore Rotation
RotationsSince an insertion/deletion involves adding/deleting a single node, this can only increase/decrease the height of some subtree by 1Thus, if the AVL tree property is violated at a node x, it means that the heights of left(x) ad right(x) differ by exactly 2.Rotations will be applied to x to restore the AVL tree property.
InsertionFirst, insert the new key as a new leaf just as in ordinary binary search treeThen trace the path from the new leaf towards the root.  For each node x encountered, check if heights of left(x) and right(x) differ by at most 1.If yes, proceed to parent(x).  If not, restructure by doing either a single rotation or a double rotation [next slide].For insertion, once we perform a rotation at a node x, we won’t need to perform any rotation at any ancestor of x.
Insertion Let x be the node at which left(x) and right(x) differ by more than 1Assume that the height of x is h+3There are 4 casesHeight of left(x) is h+2 (i.e. height of right(x) is h)Height of left(left(x)) is h+1  single rotate with left childHeight of right(left(x)) is h+1  double rotate with left childHeight of right(x) is h+2 (i.e. height of left(x) is h)Height of right(right(x)) is h+1  single rotate with right childHeight of left(right(x)) is h+1  double rotate with right childNote: Our test conditions for the 4 cases are different from the code shown in the textbook.  These conditions allow a uniform treatment between insertion and deletion.
Single rotationThe new key is inserted in the subtree A. The AVL-property is violated at x height of left(x) is h+2 height of right(x) is h.
Single rotationThe new key is inserted in the subtree C. The AVL-property is violated at x.Single rotation takes O(1) time.Insertion takes O(log N) time.
3144810.83558341x AVL Tree5Cy8BA0.8Insert 0.8After rotation
Double rotationThe new key is inserted in the subtree B1 or B2. The AVL-property is violated at x.x-y-z forms a zig-zag shapealso called left-right rotate
Double rotationThe new key is inserted in the subtree B1 or B2. The AVL-property is violated at x.also called right-left rotate
xCy3Az43.58143.5B55833415 AVL Tree8Insert 3.5After Rotation1
An Extended Example33222442211133Fig 1335Fig 4Fig 2Fig 31Fig 5Fig 6Insert 3,2,1,4,5,6,7, 16,15,14Single rotationSingle rotation
22444Fig 8Fig 755667337311222445566Fig 10Fig 95Fig 1133111Single rotationSingle rotation
4447715316316316222Fig 12Fig 131566657Fig 1455111Double rotation
4461415161533161422Fig 15Fig 167657511Double rotation
Ad

More Related Content

What's hot (20)

Binary tree
Binary tree Binary tree
Binary tree
Rajendran
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
ManishPrajapati78
 
Expression trees
Expression treesExpression trees
Expression trees
Salman Vadsarya
 
Threaded Binary Tree.pptx
Threaded Binary Tree.pptxThreaded Binary Tree.pptx
Threaded Binary Tree.pptx
pavankumarjakkepalli
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
Hossain Md Shakhawat
 
Binary trees
Binary treesBinary trees
Binary trees
Simratpreet Singh
 
Binary search tree
Binary search treeBinary search tree
Binary search tree
Kousalya M
 
Splay Tree
Splay TreeSplay Tree
Splay Tree
Dr Sandeep Kumar Poonia
 
Red Black Tree Insertion & Deletion
Red Black Tree Insertion & DeletionRed Black Tree Insertion & Deletion
Red Black Tree Insertion & Deletion
International Institute of Information Technology (I²IT)
 
Binomial Heap
Binomial HeapBinomial Heap
Binomial Heap
Goa App
 
Binary tree
Binary  treeBinary  tree
Binary tree
Vanitha Chandru
 
Binary tree
Binary treeBinary tree
Binary tree
Rajendran
 
Selection sort algorithm presentation, selection sort example using power point
Selection sort algorithm presentation, selection sort example using power point Selection sort algorithm presentation, selection sort example using power point
Selection sort algorithm presentation, selection sort example using power point
University of Science and Technology Chitttagong
 
Red black tree
Red black treeRed black tree
Red black tree
Dr Sandeep Kumar Poonia
 
Circular linked list
Circular linked listCircular linked list
Circular linked list
chauhankapil
 
Quick Sort , Merge Sort , Heap Sort
Quick Sort , Merge Sort ,  Heap SortQuick Sort , Merge Sort ,  Heap Sort
Quick Sort , Merge Sort , Heap Sort
Mohammed Hussein
 
Tree Traversal
Tree TraversalTree Traversal
Tree Traversal
Md. Israil Fakir
 
Queues
QueuesQueues
Queues
Lovely Professional University
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
Muhazzab Chouhadry
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked Lists
Afaq Mansoor Khan
 

Viewers also liked (6)

Op-Amp Fundamental
Op-Amp FundamentalOp-Amp Fundamental
Op-Amp Fundamental
Gaensan
 
Introduction to group theory
Introduction to group theoryIntroduction to group theory
Introduction to group theory
St.Marys Chemistry Department
 
Data structures
Data structuresData structures
Data structures
Saurabh Mishra
 
Operational Amplifier Part 1
Operational Amplifier Part 1Operational Amplifier Part 1
Operational Amplifier Part 1
Mukesh Tekwani
 
Data Structure
Data StructureData Structure
Data Structure
Karthikeyan A K
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURES
bca2010
 
Ad

Similar to Binary trees1 (20)

data structures module III & IV.pptx
data structures module III & IV.pptxdata structures module III & IV.pptx
data structures module III & IV.pptx
rani marri
 
Review session2
Review session2Review session2
Review session2
NEEDY12345
 
lecture 13
lecture 13lecture 13
lecture 13
sajinsc
 
Red Black Trees
Red Black TreesRed Black Trees
Red Black Trees
Varun Mahajan
 
bst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
bst-class-220902051152-cdddddddddddddddddd5e6c70f.pptbst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
bst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
shesnasuneer
 
Skiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure treesSkiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure trees
zukun
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
AdityaK92
 
Trees
TreesTrees
Trees
Ankit Sharma
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
Zafar Ayub
 
Data structures and Algorithm analysis_Lecture4.pptx
Data structures and Algorithm analysis_Lecture4.pptxData structures and Algorithm analysis_Lecture4.pptx
Data structures and Algorithm analysis_Lecture4.pptx
AhmedEldesoky24
 
Tree all information about tree concept are available .
Tree all information about tree concept are available .Tree all information about tree concept are available .
Tree all information about tree concept are available .
FaizanAhmad293255
 
Cinterviews Binarysearch Tree
Cinterviews Binarysearch TreeCinterviews Binarysearch Tree
Cinterviews Binarysearch Tree
cinterviews
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
Anusruti Mitra
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binary
SSE_AndyLi
 
CS-102 BST_27_3_14.pdf
CS-102 BST_27_3_14.pdfCS-102 BST_27_3_14.pdf
CS-102 BST_27_3_14.pdf
ssuser034ce1
 
CS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdfCS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdf
ssuser034ce1
 
mitochondria moment and super computer integration.ppt
mitochondria moment and super computer integration.pptmitochondria moment and super computer integration.ppt
mitochondria moment and super computer integration.ppt
AMMAD45
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
worldchannel
 
bst.ppt
bst.pptbst.ppt
bst.ppt
plagcheck
 
Balance tree. Short overview
Balance tree. Short overviewBalance tree. Short overview
Balance tree. Short overview
ElifTech
 
data structures module III & IV.pptx
data structures module III & IV.pptxdata structures module III & IV.pptx
data structures module III & IV.pptx
rani marri
 
Review session2
Review session2Review session2
Review session2
NEEDY12345
 
lecture 13
lecture 13lecture 13
lecture 13
sajinsc
 
bst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
bst-class-220902051152-cdddddddddddddddddd5e6c70f.pptbst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
bst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
shesnasuneer
 
Skiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure treesSkiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure trees
zukun
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
AdityaK92
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
Zafar Ayub
 
Data structures and Algorithm analysis_Lecture4.pptx
Data structures and Algorithm analysis_Lecture4.pptxData structures and Algorithm analysis_Lecture4.pptx
Data structures and Algorithm analysis_Lecture4.pptx
AhmedEldesoky24
 
Tree all information about tree concept are available .
Tree all information about tree concept are available .Tree all information about tree concept are available .
Tree all information about tree concept are available .
FaizanAhmad293255
 
Cinterviews Binarysearch Tree
Cinterviews Binarysearch TreeCinterviews Binarysearch Tree
Cinterviews Binarysearch Tree
cinterviews
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
Anusruti Mitra
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binary
SSE_AndyLi
 
CS-102 BST_27_3_14.pdf
CS-102 BST_27_3_14.pdfCS-102 BST_27_3_14.pdf
CS-102 BST_27_3_14.pdf
ssuser034ce1
 
CS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdfCS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdf
ssuser034ce1
 
mitochondria moment and super computer integration.ppt
mitochondria moment and super computer integration.pptmitochondria moment and super computer integration.ppt
mitochondria moment and super computer integration.ppt
AMMAD45
 
Balance tree. Short overview
Balance tree. Short overviewBalance tree. Short overview
Balance tree. Short overview
ElifTech
 
Ad

More from Saurabh Mishra (7)

Sorting2
Sorting2Sorting2
Sorting2
Saurabh Mishra
 
Sorting
SortingSorting
Sorting
Saurabh Mishra
 
Searching
SearchingSearching
Searching
Saurabh Mishra
 
Presentation1
Presentation1Presentation1
Presentation1
Saurabh Mishra
 
Graps 2
Graps 2Graps 2
Graps 2
Saurabh Mishra
 
Graphs
GraphsGraphs
Graphs
Saurabh Mishra
 
Trees
TreesTrees
Trees
Saurabh Mishra
 

Recently uploaded (20)

Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 

Binary trees1

  • 2. TreesLinear access time of linked lists is prohibitiveDoes there exist any simple data structure for which the running time of most operations (search, insert, delete) is O(log N)?
  • 3. TreesA tree is a collection of nodesThe collection can be empty(recursive definition) If not empty, a tree consists of a distinguished node r (the root), and zero or more nonempty subtrees T1, T2, ...., Tk, each of whose roots are connected by a directed edge from r
  • 4. Some TerminologiesChild and parentEvery node except the root has one parent A node can have an arbitrary number of childrenLeavesNodes with no children Siblingnodes with same parent
  • 5. Some TerminologiesPathLengthnumber of edges on the pathDepthof a nodelength of the unique path from the root to that nodeThe depth of a tree is equal to the depth of the deepest leafHeight of a nodelength of the longest path from that node to a leafall leaves are at height 0The height of a tree is equal to the height of the rootAncestor and descendantProper ancestor and proper descendant
  • 7. Binary TreesA tree in which no node can have more than two childrenThe depth of an “average” binary tree is considerably smaller than N, eventhough in the worst case, the depth can be as large as N – 1.
  • 8. Example: Expression TreesLeaves are operands (constants or variables)The other nodes (internal nodes) contain operatorsWill not be a binary tree if some operators are not binary
  • 9. Tree traversalUsed to print out the data in a tree in a certain orderPre-order traversalPrint the data at the rootRecursively print out all data in the left subtreeRecursively print out all data in the right subtree
  • 10. Preorder, Postorder and InorderPreorder traversalnode, left, rightprefix expression++a*bc*+*defg
  • 11. Preorder, Postorder and InorderPostorder traversalleft, right, nodepostfix expressionabc*+de*f+g*+Inorder traversalleft, node, right.infix expressiona+b*c+d*e+f*g
  • 15. Binary TreesPossible operations on the Binary Tree ADTparentleft_child, right_childsiblingroot, etcImplementationBecause a binary tree has at most two children, we can keep direct pointers to them
  • 16. compare: Implementation of a general tree
  • 17. Binary Search TreesStores keys in the nodes in a way so that searching, insertion and deletion can be done efficiently.Binary search tree propertyFor every node X, all the keys in its left subtree are smaller than the key value in X, and all the keys in its right subtree are larger than the key value in X
  • 18. Binary Search TreesA binary search treeNot a binary search tree
  • 19. Binary search treesAverage depth of a node is O(log N); maximum depth of a node is O(N)Two binary search trees representing the same set:
  • 21. Searching BSTIf we are searching for 15, then we are done.If we are searching for a key < 15, then we should search in the left subtree.If we are searching for a key > 15, then we should search in the right subtree.
  • 23. Searching (Find)Find X: return a pointer to the node that has key X, or NULL if there is no such nodeTime complexityO(height of the tree)
  • 24. Inorder traversal of BSTPrint out all the keys in sorted orderInorder: 2, 3, 4, 6, 7, 9, 13, 15, 17, 18, 20
  • 25. findMin/ findMaxReturn the node containing the smallest element in the treeStart at the root and go left as long as there is a left child. The stopping point is the smallest elementSimilarly for findMaxTime complexity = O(height of the tree)
  • 26. insertProceed down the tree as you would with a findIf X is found, do nothing (or update something)Otherwise, insert X at the last spot on the path traversedTime complexity = O(height of the tree)
  • 27. deleteWhen we delete a node, we need to consider how we take care of the children of the deleted node.This has to be done such that the property of the search tree is maintained.
  • 28. deleteThree cases:(1) the node is a leafDelete it immediately(2) the node has one childAdjust a pointer from the parent to bypass that node
  • 29. delete(3) the node has 2 childrenreplace the key of that node with the minimum element at the right subtree delete the minimum element Has either no child or only right child because if it has a left child, that left child would be smaller and would have been chosen. So invoke case 1 or 2.Time complexity = O(height of the tree)
  • 31. Balanced binary treeThe disadvantage of a binary search tree is that its height can be as large as N-1This means that the time needed to perform insertion and deletion and many other operations can be O(N) in the worst caseWe want a tree with small heightA binary tree with N node has height at least(log N) Thus, our goal is to keep the height of a binary search tree O(log N)Such trees are called balanced binary search trees. Examples are AVL tree, red-black tree.
  • 32. AVL treeHeight of a nodeThe height of a leaf is 1. The height of a null pointer is zero.The height of an internal node is the maximum height of its children plus 1Note that this definition of height is different from the one we defined previously (we defined the height of a leaf as zero previously).
  • 33. AVL treeAn AVL tree is a binary search tree in whichfor every node in the tree, the height of the left and right subtrees differ by at most 1.AVL property violated here
  • 34. AVL treeLet x be the root of an AVL tree of height hLet Nh denote the minimum number of nodes in an AVL tree of height hClearly, Ni≥ Ni-1 by definitionWe haveBy repeated substitution, we obtain the general formThe boundary conditions are: N1=1 and N2 =2. This implies that h = O(log Nh).Thus, many operations (searching, insertion, deletion) on an AVL tree will take O(log N) time.
  • 35. RotationsWhen the tree structure changes (e.g., insertion or deletion), we need to transform the tree to restore the AVL tree property.This is done using single rotations or double rotations.yxACBe.g. Single RotationxyCBAAfter RotationBefore Rotation
  • 36. RotationsSince an insertion/deletion involves adding/deleting a single node, this can only increase/decrease the height of some subtree by 1Thus, if the AVL tree property is violated at a node x, it means that the heights of left(x) ad right(x) differ by exactly 2.Rotations will be applied to x to restore the AVL tree property.
  • 37. InsertionFirst, insert the new key as a new leaf just as in ordinary binary search treeThen trace the path from the new leaf towards the root. For each node x encountered, check if heights of left(x) and right(x) differ by at most 1.If yes, proceed to parent(x). If not, restructure by doing either a single rotation or a double rotation [next slide].For insertion, once we perform a rotation at a node x, we won’t need to perform any rotation at any ancestor of x.
  • 38. Insertion Let x be the node at which left(x) and right(x) differ by more than 1Assume that the height of x is h+3There are 4 casesHeight of left(x) is h+2 (i.e. height of right(x) is h)Height of left(left(x)) is h+1  single rotate with left childHeight of right(left(x)) is h+1  double rotate with left childHeight of right(x) is h+2 (i.e. height of left(x) is h)Height of right(right(x)) is h+1  single rotate with right childHeight of left(right(x)) is h+1  double rotate with right childNote: Our test conditions for the 4 cases are different from the code shown in the textbook. These conditions allow a uniform treatment between insertion and deletion.
  • 39. Single rotationThe new key is inserted in the subtree A. The AVL-property is violated at x height of left(x) is h+2 height of right(x) is h.
  • 40. Single rotationThe new key is inserted in the subtree C. The AVL-property is violated at x.Single rotation takes O(1) time.Insertion takes O(log N) time.
  • 42. Double rotationThe new key is inserted in the subtree B1 or B2. The AVL-property is violated at x.x-y-z forms a zig-zag shapealso called left-right rotate
  • 43. Double rotationThe new key is inserted in the subtree B1 or B2. The AVL-property is violated at x.also called right-left rotate
  • 45. An Extended Example33222442211133Fig 1335Fig 4Fig 2Fig 31Fig 5Fig 6Insert 3,2,1,4,5,6,7, 16,15,14Single rotationSingle rotation
  • 46. 22444Fig 8Fig 755667337311222445566Fig 10Fig 95Fig 1133111Single rotationSingle rotation