SlideShare a Scribd company logo
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

Cinterviews Binarysearch Tree
Cinterviews Binarysearch TreeCinterviews Binarysearch Tree
Cinterviews Binarysearch Tree
cinterviews
 
Binary tree
Binary  treeBinary  tree
Binary tree
Vanitha Chandru
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
Shivam Singh
 
Binary search trees
Binary search treesBinary search trees
Binary search trees
Dhananjaysinh Jhala
 
Binary trees1
Binary trees1Binary trees1
Binary trees1
Saurabh Mishra
 
Binary tree
Binary tree Binary tree
Binary tree
Rajendran
 
Chapter 8 ds
Chapter 8 dsChapter 8 ds
Chapter 8 ds
Hanif Durad
 
Tree
TreeTree
Binary tree and Binary search tree
Binary tree and Binary search treeBinary tree and Binary search tree
Binary tree and Binary search tree
Mayeesha Samiha
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
ER Punit Jain
 
Binary Search Tree (BST)
Binary Search Tree (BST)Binary Search Tree (BST)
Binary Search Tree (BST)
M Sajid R
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
shameen khan
 
data structure(tree operations)
data structure(tree operations)data structure(tree operations)
data structure(tree operations)
Waheed Khalid
 
Trees
TreesTrees
Tree data structure
Tree data structureTree data structure
Tree data structureDana dia
 
Tree
TreeTree
Data Structure and Algorithms Binary Tree
Data Structure and Algorithms Binary TreeData Structure and Algorithms Binary Tree
Data Structure and Algorithms Binary Tree
ManishPrajapati78
 
Lecture 8 data structures and algorithms
Lecture 8 data structures and algorithmsLecture 8 data structures and algorithms
Lecture 8 data structures and algorithmsAakash deep Singhal
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
Krish_ver2
 

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 Jitescript
Joe Kutner
 
Threads
ThreadsThreads
Threads
Nilesh Jha
 
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
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
Java Notes
Java NotesJava Notes
Java Notes
Abhishek Khune
 
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

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
nakulvarshney371
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docx
sowmya koneru
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
Zafar Ayub
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
Anusruti Mitra
 
Dsc++ unit 3 notes
Dsc++ unit 3 notesDsc++ unit 3 notes
Dsc++ unit 3 notes
Guru Nanak Institute Of Tech
 
Lecture 5 tree.pptx
Lecture 5 tree.pptxLecture 5 tree.pptx
Lecture 5 tree.pptx
Abirami A
 
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
Ramco Institute of Technology, Rajapalayam, Tamilnadu, India
 
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
RupaRaj6
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptx
skilljiolms
 
UNIT-4 TREES.ppt
UNIT-4 TREES.pptUNIT-4 TREES.ppt
UNIT-4 TREES.ppt
SIVAKUMARM603675
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
worldchannel
 
Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal Khan
Daniyal Khan
 
Trees
TreesTrees
Tree data structure.pptx
Tree data structure.pptxTree data structure.pptx
Tree data structure.pptx
ssuser039bf6
 
NON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptxNON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptx
Rajitha Reddy Alugati
 
Farhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructureFarhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructure
Farhana Shaikh
 
Unit 5 Tree.pptx
Unit 5 Tree.pptxUnit 5 Tree.pptx
Unit 5 Tree.pptx
SurajSharma266169
 
nptel 2nd presentation.pptx
nptel 2nd presentation.pptxnptel 2nd presentation.pptx
nptel 2nd presentation.pptx
KeshavBandil2
 
Trees.pptx
Trees.pptxTrees.pptx

Similar to 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
 

More from Abhishek Khune

Clanguage
ClanguageClanguage
Clanguage
Abhishek Khune
 
Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)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

Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 

Recently uploaded (20)

Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 

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