SlideShare a Scribd company logo
1 of 18
Binary TreesBinary Trees
Chapter 6Chapter 6
Linked Lists SuckLinked Lists Suck
 By now you realize that the title to this slide isBy now you realize that the title to this slide is
true…true…
 When we are talking about searching orWhen we are talking about searching or
representing data structures that need arepresenting data structures that need a
hierarchical structures.hierarchical structures.
 We need a better structure…We need a better structure…
 So we get binary treesSo we get binary trees
Tree definitionTree definition
 Here is a (recursive, of course) definition forHere is a (recursive, of course) definition for
a tree:a tree:
1.1. An empty structure is an empty treeAn empty structure is an empty tree
2.2. If t1,…,tk are disjointed trees, then theIf t1,…,tk are disjointed trees, then the
structure whose root has as its children thestructure whose root has as its children the
roots of t1,…,tk is also a treeroots of t1,…,tk is also a tree
3.3. Only structures generate by rules 1 and 2 areOnly structures generate by rules 1 and 2 are
trees.trees.
More terminologyMore terminology
 Each node has to be reachable from the rootsEach node has to be reachable from the roots
through a unique sequence of arcs called athrough a unique sequence of arcs called a
path.path.
 The number of arcs in a path is called theThe number of arcs in a path is called the
length of the path.length of the path.
 The level of a node is the length of the pathThe level of a node is the length of the path
from the root to the node plus 1.from the root to the node plus 1.
 The height of a non-empty tree is theThe height of a non-empty tree is the
maximum level of a node in the tree.maximum level of a node in the tree.
Special TreesSpecial Trees
 An empty tree has a height of zero.An empty tree has a height of zero.
 A single node tree is a tree of height 1.A single node tree is a tree of height 1.
 This is the only case where a node is both a rootThis is the only case where a node is both a root
and a leaf.and a leaf.
Binary TreesBinary Trees
 According to the definition of trees, a node canAccording to the definition of trees, a node can
have any number of children.have any number of children.
 A binary tree is restricted to only having 0, 1,A binary tree is restricted to only having 0, 1,
or 2 children.or 2 children.
 A complete binary tree is one where all theA complete binary tree is one where all the
levels are full with exception to the last levellevels are full with exception to the last level
and it is filled from left to right.and it is filled from left to right.
 A full binary tree is one where if a node has aA full binary tree is one where if a node has a
child, then it has two children.child, then it has two children.
Full Binary Tree TheoremFull Binary Tree Theorem
 For all the nonempty binary trees whoseFor all the nonempty binary trees whose
nonterminal node have exactly two nonemptynonterminal node have exactly two nonempty
children, the number of leaveschildren, the number of leaves mm is greateris greater
than the number of nonterminal nodethan the number of nonterminal node kk andand mm
== kk + 1.+ 1.
Binary Search TreesBinary Search Trees
 A binary search tree (BST) is a binary tree thatA binary search tree (BST) is a binary tree that
has the following property: For each nodehas the following property: For each node nn ofof
the tree, all values stored in its left subtree arethe tree, all values stored in its left subtree are
less than valueless than value vv stored instored in nn, and all values, and all values
stored in the right subtree are greater thanstored in the right subtree are greater than vv..
 This definition excludes the case of duplicates.This definition excludes the case of duplicates.
They can be include and would be put in theThey can be include and would be put in the
right subtree.right subtree.
Binary Tree TraversalsBinary Tree Traversals
 A traversal is where each node in a tree isA traversal is where each node in a tree is
visited and visited oncevisited and visited once
 For a tree of n nodes there are n! traversalsFor a tree of n nodes there are n! traversals
 Of course most of those are hard to programOf course most of those are hard to program
 There are two very common traversalsThere are two very common traversals
 Breadth FirstBreadth First
 Depth FirstDepth First
Breadth FirstBreadth First
 In a breadth first traversal all of the nodes on aIn a breadth first traversal all of the nodes on a
given level are visited and then all of the nodesgiven level are visited and then all of the nodes
on the next level are visited.on the next level are visited.
 Usually in a left to right fashionUsually in a left to right fashion
 This is implemented with a queueThis is implemented with a queue
Depth FirstDepth First
 In a depth first traversal all the nodes on aIn a depth first traversal all the nodes on a
branch are visited before any others are visitedbranch are visited before any others are visited
 There are three common depth first traversalsThere are three common depth first traversals
 InorderInorder
 PreorderPreorder
 PostorderPostorder
 Each type has its use and specific applicationEach type has its use and specific application
InsertionInsertion
 In order to build a tree you must be able toIn order to build a tree you must be able to
insert into the treeinsert into the tree
 In order to do this you need to know where theIn order to do this you need to know where the
nodes goesnodes goes
 Typically the tree is searched looking for aTypically the tree is searched looking for a
null pointer to hang the new element fromnull pointer to hang the new element from
 There are two common ways to do thisThere are two common ways to do this
 Use a look ahead or check for null as the firstUse a look ahead or check for null as the first
line in the codeline in the code
More insertionMore insertion
 I prefer to check for null as the first thing I doI prefer to check for null as the first thing I do
in my codein my code
 It simplifies some of the testsIt simplifies some of the tests
 And makes for a really easy to check for baseAnd makes for a really easy to check for base
casecase
CodeCode
InsertionHelper( Node *n, T data )InsertionHelper( Node *n, T data )
{{
if ( node == 0 )if ( node == 0 )
return new Node( data );return new Node( data );
if ( n->getData() < data )if ( n->getData() < data )
setLeft( InsertionHelper( n->getLeft(), data);setLeft( InsertionHelper( n->getLeft(), data);
elseelse
setRight( InsertionHelper( n->getRight(), data);setRight( InsertionHelper( n->getRight(), data);
}}
DeletionDeletion
 Deletion poses a bigger problemDeletion poses a bigger problem
 When we delete we normally have two choicesWhen we delete we normally have two choices
 Deletion by mergingDeletion by merging
 Deletion by copyingDeletion by copying
Deletion by MergingDeletion by Merging
 Deletion by merging takes two subtrees andDeletion by merging takes two subtrees and
merges them together into one treemerges them together into one tree
 The idea is you have a node n to deleteThe idea is you have a node n to delete
 N can have two childrenN can have two children
 So you find the smallest element in n’s leftSo you find the smallest element in n’s left
subtreesubtree
 You then take n’s right subtree and merge it toYou then take n’s right subtree and merge it to
the bottom of the left subtreethe bottom of the left subtree
 The root of the left subtree replaces nThe root of the left subtree replaces n
Deletion by copyingDeletion by copying
 This will simply swap values and reduce aThis will simply swap values and reduce a
difficult case to an easier onedifficult case to an easier one
 If the node n to be deleted has no children,If the node n to be deleted has no children,
 easy blow it awayeasy blow it away
 If it has one childIf it has one child
 Easy simply pass n’s child pointer up, make n’sEasy simply pass n’s child pointer up, make n’s
parent point to n’s child and blow n awayparent point to n’s child and blow n away
 If n has two child,If n has two child,
 Now we have deletion by copyingNow we have deletion by copying
DetailsDetails
 We find the smallest value in n’s right subtreeWe find the smallest value in n’s right subtree
 We will take the value from that node and putWe will take the value from that node and put
it in place of the value in nit in place of the value in n
 We will then blow away the node that had theWe will then blow away the node that had the
smallest value in itsmallest value in it

More Related Content

What's hot

What's hot (20)

Cinterviews Binarysearch Tree
Cinterviews Binarysearch TreeCinterviews Binarysearch Tree
Cinterviews Binarysearch Tree
 
Binary tree
Binary  treeBinary  tree
Binary tree
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Binary search trees
Binary search treesBinary search trees
Binary search trees
 
Binary trees1
Binary trees1Binary trees1
Binary trees1
 
Binary tree
Binary tree Binary tree
Binary tree
 
Chapter 8 ds
Chapter 8 dsChapter 8 ds
Chapter 8 ds
 
Tree
TreeTree
Tree
 
Binary tree and Binary search tree
Binary tree and Binary search treeBinary tree and Binary search tree
Binary tree and Binary search tree
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
 
Binary Search Tree (BST)
Binary Search Tree (BST)Binary Search Tree (BST)
Binary Search Tree (BST)
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
data structure(tree operations)
data structure(tree operations)data structure(tree operations)
data structure(tree operations)
 
binary tree
binary treebinary tree
binary tree
 
Trees
TreesTrees
Trees
 
Tree data structure
Tree data structureTree data structure
Tree data structure
 
Tree
TreeTree
Tree
 
Data Structure and Algorithms Binary Tree
Data Structure and Algorithms Binary TreeData Structure and Algorithms Binary Tree
Data Structure and Algorithms Binary Tree
 
Lecture 8 data structures and algorithms
Lecture 8 data structures and algorithmsLecture 8 data structures and algorithms
Lecture 8 data structures and algorithms
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 

Viewers also liked

Lecture on Java Concurrency Day 3 on Feb 11, 2009.
Lecture on Java Concurrency Day 3 on Feb 11, 2009.Lecture on Java Concurrency Day 3 on Feb 11, 2009.
Lecture on Java Concurrency Day 3 on Feb 11, 2009.Kyung Koo Yoon
 
Programming JVM Bytecode with Jitescript
Programming JVM Bytecode with JitescriptProgramming JVM Bytecode with Jitescript
Programming JVM Bytecode with JitescriptJoe Kutner
 
Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01Abhishek Khune
 
Multithreaded programming (as part of the the PTT lecture)
Multithreaded programming (as part of the the PTT lecture)Multithreaded programming (as part of the the PTT lecture)
Multithreaded programming (as part of the the PTT lecture)Ralf Laemmel
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 

Viewers also liked (14)

Lecture on Java Concurrency Day 3 on Feb 11, 2009.
Lecture on Java Concurrency Day 3 on Feb 11, 2009.Lecture on Java Concurrency Day 3 on Feb 11, 2009.
Lecture on Java Concurrency Day 3 on Feb 11, 2009.
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Threads
ThreadsThreads
Threads
 
Week0 introduction
Week0 introductionWeek0 introduction
Week0 introduction
 
Programming JVM Bytecode with Jitescript
Programming JVM Bytecode with JitescriptProgramming JVM Bytecode with Jitescript
Programming JVM Bytecode with Jitescript
 
Threads
ThreadsThreads
Threads
 
Sorting
SortingSorting
Sorting
 
Shared memory
Shared memoryShared memory
Shared memory
 
Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01
 
Multithreaded programming (as part of the the PTT lecture)
Multithreaded programming (as part of the the PTT lecture)Multithreaded programming (as part of the the PTT lecture)
Multithreaded programming (as part of the the PTT lecture)
 
07 java collection
07 java collection07 java collection
07 java collection
 
Java Notes
Java NotesJava Notes
Java Notes
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 

Similar to Binary Trees Chapter - Linked Lists Suck, Binary Trees Are Better

Similar to Binary Trees Chapter - Linked Lists Suck, Binary Trees Are Better (20)

Final tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationFinal tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentation
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docx
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
 
Dsc++ unit 3 notes
Dsc++ unit 3 notesDsc++ unit 3 notes
Dsc++ unit 3 notes
 
Lecture 5 tree.pptx
Lecture 5 tree.pptxLecture 5 tree.pptx
Lecture 5 tree.pptx
 
AD3251-Data Structures Design-Notes-Tree.pdf
AD3251-Data Structures  Design-Notes-Tree.pdfAD3251-Data Structures  Design-Notes-Tree.pdf
AD3251-Data Structures Design-Notes-Tree.pdf
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptx
 
Trees
TreesTrees
Trees
 
UNIT-4 TREES.ppt
UNIT-4 TREES.pptUNIT-4 TREES.ppt
UNIT-4 TREES.ppt
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 
Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal Khan
 
Trees
TreesTrees
Trees
 
Tree data structure.pptx
Tree data structure.pptxTree data structure.pptx
Tree data structure.pptx
 
NON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptxNON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptx
 
Farhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructureFarhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructure
 
Unit 5 Tree.pptx
Unit 5 Tree.pptxUnit 5 Tree.pptx
Unit 5 Tree.pptx
 
nptel 2nd presentation.pptx
nptel 2nd presentation.pptxnptel 2nd presentation.pptx
nptel 2nd presentation.pptx
 
Trees.pptx
Trees.pptxTrees.pptx
Trees.pptx
 
Unit 3,4.docx
Unit 3,4.docxUnit 3,4.docx
Unit 3,4.docx
 

More from Abhishek Khune

More from Abhishek Khune (8)

Clanguage
ClanguageClanguage
Clanguage
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Applets
AppletsApplets
Applets
 
Clanguage
ClanguageClanguage
Clanguage
 
Java unit3
Java unit3Java unit3
Java unit3
 
Java unit2
Java unit2Java unit2
Java unit2
 
Linux introduction
Linux introductionLinux introduction
Linux introduction
 
Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)
 

Recently uploaded

Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxleah joy valeriano
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 

Recently uploaded (20)

Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 

Binary Trees Chapter - Linked Lists Suck, Binary Trees Are Better

  • 2. Linked Lists SuckLinked Lists Suck  By now you realize that the title to this slide isBy now you realize that the title to this slide is true…true…  When we are talking about searching orWhen we are talking about searching or representing data structures that need arepresenting data structures that need a hierarchical structures.hierarchical structures.  We need a better structure…We need a better structure…  So we get binary treesSo we get binary trees
  • 3. Tree definitionTree definition  Here is a (recursive, of course) definition forHere is a (recursive, of course) definition for a tree:a tree: 1.1. An empty structure is an empty treeAn empty structure is an empty tree 2.2. If t1,…,tk are disjointed trees, then theIf t1,…,tk are disjointed trees, then the structure whose root has as its children thestructure whose root has as its children the roots of t1,…,tk is also a treeroots of t1,…,tk is also a tree 3.3. Only structures generate by rules 1 and 2 areOnly structures generate by rules 1 and 2 are trees.trees.
  • 4. More terminologyMore terminology  Each node has to be reachable from the rootsEach node has to be reachable from the roots through a unique sequence of arcs called athrough a unique sequence of arcs called a path.path.  The number of arcs in a path is called theThe number of arcs in a path is called the length of the path.length of the path.  The level of a node is the length of the pathThe level of a node is the length of the path from the root to the node plus 1.from the root to the node plus 1.  The height of a non-empty tree is theThe height of a non-empty tree is the maximum level of a node in the tree.maximum level of a node in the tree.
  • 5. Special TreesSpecial Trees  An empty tree has a height of zero.An empty tree has a height of zero.  A single node tree is a tree of height 1.A single node tree is a tree of height 1.  This is the only case where a node is both a rootThis is the only case where a node is both a root and a leaf.and a leaf.
  • 6. Binary TreesBinary Trees  According to the definition of trees, a node canAccording to the definition of trees, a node can have any number of children.have any number of children.  A binary tree is restricted to only having 0, 1,A binary tree is restricted to only having 0, 1, or 2 children.or 2 children.  A complete binary tree is one where all theA complete binary tree is one where all the levels are full with exception to the last levellevels are full with exception to the last level and it is filled from left to right.and it is filled from left to right.  A full binary tree is one where if a node has aA full binary tree is one where if a node has a child, then it has two children.child, then it has two children.
  • 7. Full Binary Tree TheoremFull Binary Tree Theorem  For all the nonempty binary trees whoseFor all the nonempty binary trees whose nonterminal node have exactly two nonemptynonterminal node have exactly two nonempty children, the number of leaveschildren, the number of leaves mm is greateris greater than the number of nonterminal nodethan the number of nonterminal node kk andand mm == kk + 1.+ 1.
  • 8. Binary Search TreesBinary Search Trees  A binary search tree (BST) is a binary tree thatA binary search tree (BST) is a binary tree that has the following property: For each nodehas the following property: For each node nn ofof the tree, all values stored in its left subtree arethe tree, all values stored in its left subtree are less than valueless than value vv stored instored in nn, and all values, and all values stored in the right subtree are greater thanstored in the right subtree are greater than vv..  This definition excludes the case of duplicates.This definition excludes the case of duplicates. They can be include and would be put in theThey can be include and would be put in the right subtree.right subtree.
  • 9. Binary Tree TraversalsBinary Tree Traversals  A traversal is where each node in a tree isA traversal is where each node in a tree is visited and visited oncevisited and visited once  For a tree of n nodes there are n! traversalsFor a tree of n nodes there are n! traversals  Of course most of those are hard to programOf course most of those are hard to program  There are two very common traversalsThere are two very common traversals  Breadth FirstBreadth First  Depth FirstDepth First
  • 10. Breadth FirstBreadth First  In a breadth first traversal all of the nodes on aIn a breadth first traversal all of the nodes on a given level are visited and then all of the nodesgiven level are visited and then all of the nodes on the next level are visited.on the next level are visited.  Usually in a left to right fashionUsually in a left to right fashion  This is implemented with a queueThis is implemented with a queue
  • 11. Depth FirstDepth First  In a depth first traversal all the nodes on aIn a depth first traversal all the nodes on a branch are visited before any others are visitedbranch are visited before any others are visited  There are three common depth first traversalsThere are three common depth first traversals  InorderInorder  PreorderPreorder  PostorderPostorder  Each type has its use and specific applicationEach type has its use and specific application
  • 12. InsertionInsertion  In order to build a tree you must be able toIn order to build a tree you must be able to insert into the treeinsert into the tree  In order to do this you need to know where theIn order to do this you need to know where the nodes goesnodes goes  Typically the tree is searched looking for aTypically the tree is searched looking for a null pointer to hang the new element fromnull pointer to hang the new element from  There are two common ways to do thisThere are two common ways to do this  Use a look ahead or check for null as the firstUse a look ahead or check for null as the first line in the codeline in the code
  • 13. More insertionMore insertion  I prefer to check for null as the first thing I doI prefer to check for null as the first thing I do in my codein my code  It simplifies some of the testsIt simplifies some of the tests  And makes for a really easy to check for baseAnd makes for a really easy to check for base casecase
  • 14. CodeCode InsertionHelper( Node *n, T data )InsertionHelper( Node *n, T data ) {{ if ( node == 0 )if ( node == 0 ) return new Node( data );return new Node( data ); if ( n->getData() < data )if ( n->getData() < data ) setLeft( InsertionHelper( n->getLeft(), data);setLeft( InsertionHelper( n->getLeft(), data); elseelse setRight( InsertionHelper( n->getRight(), data);setRight( InsertionHelper( n->getRight(), data); }}
  • 15. DeletionDeletion  Deletion poses a bigger problemDeletion poses a bigger problem  When we delete we normally have two choicesWhen we delete we normally have two choices  Deletion by mergingDeletion by merging  Deletion by copyingDeletion by copying
  • 16. Deletion by MergingDeletion by Merging  Deletion by merging takes two subtrees andDeletion by merging takes two subtrees and merges them together into one treemerges them together into one tree  The idea is you have a node n to deleteThe idea is you have a node n to delete  N can have two childrenN can have two children  So you find the smallest element in n’s leftSo you find the smallest element in n’s left subtreesubtree  You then take n’s right subtree and merge it toYou then take n’s right subtree and merge it to the bottom of the left subtreethe bottom of the left subtree  The root of the left subtree replaces nThe root of the left subtree replaces n
  • 17. Deletion by copyingDeletion by copying  This will simply swap values and reduce aThis will simply swap values and reduce a difficult case to an easier onedifficult case to an easier one  If the node n to be deleted has no children,If the node n to be deleted has no children,  easy blow it awayeasy blow it away  If it has one childIf it has one child  Easy simply pass n’s child pointer up, make n’sEasy simply pass n’s child pointer up, make n’s parent point to n’s child and blow n awayparent point to n’s child and blow n away  If n has two child,If n has two child,  Now we have deletion by copyingNow we have deletion by copying
  • 18. DetailsDetails  We find the smallest value in n’s right subtreeWe find the smallest value in n’s right subtree  We will take the value from that node and putWe will take the value from that node and put it in place of the value in nit in place of the value in n  We will then blow away the node that had theWe will then blow away the node that had the smallest value in itsmallest value in it