SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

Tendances (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
 

En vedette

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
 

En vedette (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
 

Similaire à Binary trees

Similaire à Binary trees (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
 
tree Data Structures in python Traversals.pptx
tree Data Structures in python Traversals.pptxtree Data Structures in python Traversals.pptx
tree Data Structures in python Traversals.pptx
 
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
 

Plus de Abhishek Khune

Plus de 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)
 

Dernier

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 

Dernier (20)

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 

Binary trees

  • 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