SlideShare a Scribd company logo
1 of 13
Data Structures
Trees
Summary
• Topics
• general trees, definitions and properties
• interface and implementation
• tree traversal algorithms
• depth and height
• pre-order traversal
• post-order traversal
Trees
• So far we have seen linear structures
• linear: before and after relationship
• lists, vectors, arrays, stacks, queues, etc
• Non-linear structure: trees
• probably the most fundamental structure in
computing
• hierarchical structure
• Terminology: from family trees (genealogy)
root
Trees
• store elements hierarchically
• the top element: root
• except the root, each element has a parent
• each element has 0 or more children
Trees
• Definition
• A tree T is a set of nodes storing elements such that the
nodes have a parent-child relationship that satisfies the following
• if T is not empty, T has a special tree called the root that has no parent
• each node v of T different than the root has a unique parent node
w; each node with parent w is a child of w
• Recursive definition
• T is either empty
• or consists of a node r (the root) and a possibly empty set of
trees whose roots are the children of r
• Terminology
• siblings: two nodes that have the same parent are called siblings
• internal nodes
• nodes that have children
• external nodes or leaves
• nodes that don’t have children
• ancestors
• descendants
Trees
root
inter
nal nodes
leav
es
Trees
ancestors of u
u
Trees
descendants of u
u
Application of trees
• Applications of trees
• class hierarchy
in Java
• file system
• storing
hierarchies in
organizations
Tree ADT
• Whatever the implementation of a tree is, its interface is
the following
• root()
• size()
• isEmpty()
• parent(v)
• children(v)
• isInternal(v)
• isExternal(v)
• isRoot()
Algorithms on trees
• Definition:
• depth(T, v) is the number of ancestors of v, excluding v itself
• //compute the depth of a node v in tree T
• int depth(T, v)
• recursive formulation
• if v == root, then depth(v) = 0
• else, depth(v) is 1 + depth (parent(v))
• Algorithm:
int depth(T,v) {
if T.isRoot(v) return 0
return 1 + depth(T, T.parent(v))
}
• Analysis:
• O(number of ancestors) = O(depth_v)
• in the worst case the path is a linked-list and v is the leaf
• ==> O(n), where n is the number of nodes in the tree
Algorithms on trees
• Definition:
• height of a node v in T is the length of the longest path from v to any leaf
• //compute the height of tree T
• int height(T,v)
• recursive definition:
• if v is leaf, then its height is 0
• else height(v) = 1 + maximum height of a child of v
• definition:
• the height of a tree is the height of its root
• Proposition: the height of a tree T is the maximum depth of one of its leaves.
Height
• Algorithm:
int height(T,v) {
if T.isExternal(v) return 0;
int h = 0;
for each child w of v in T do
h = max(h, height(T, w))
return h+1;
}
• Analysis:
• total time: the sum of times spent at each
node, for all nodes
• the algorithm is recursive;
• v calls height(w) on all children w of v
• height() will eventually be called on
every descendant of v
• is called on each node precisely once,
because each node has one parent
• aside from recursion
• for each node v: go through all
children of v
• O(1 + c_v) where c_v is the
number of children of v
• over all nodes: O(n) + SUM (c_v)
• each node is child of only one
node, so its processed once as a

More Related Content

What's hot (16)

Using Linked Data Traversal to Label Academic Communities - SAVE-SD2015
Using Linked Data Traversal to Label Academic Communities - SAVE-SD2015Using Linked Data Traversal to Label Academic Communities - SAVE-SD2015
Using Linked Data Traversal to Label Academic Communities - SAVE-SD2015
 
Search tree & graph
Search tree & graphSearch tree & graph
Search tree & graph
 
Mca iii dfs u-4 tree and graph
Mca iii dfs u-4 tree and graphMca iii dfs u-4 tree and graph
Mca iii dfs u-4 tree and graph
 
Introduction to tree ds
Introduction to tree dsIntroduction to tree ds
Introduction to tree ds
 
Data structures 3
Data structures 3Data structures 3
Data structures 3
 
Trees krw
Trees krwTrees krw
Trees krw
 
introduction to_trees
introduction to_treesintroduction to_trees
introduction to_trees
 
Loops and arrays
Loops and arraysLoops and arrays
Loops and arrays
 
Data structure day1
Data structure day1Data structure day1
Data structure day1
 
Tree basics
Tree basicsTree basics
Tree basics
 
Red black trees
Red black treesRed black trees
Red black trees
 
Atlas.Ti Summary
Atlas.Ti SummaryAtlas.Ti Summary
Atlas.Ti Summary
 
Tree(Data Structure)
Tree(Data Structure)Tree(Data Structure)
Tree(Data Structure)
 
Graph & Heap in Data Structure (Basic Information)
Graph & Heap in Data Structure (Basic Information)Graph & Heap in Data Structure (Basic Information)
Graph & Heap in Data Structure (Basic Information)
 
L 15 ct1120
L 15 ct1120L 15 ct1120
L 15 ct1120
 
Quantifying the bias in data links
Quantifying the bias in data linksQuantifying the bias in data links
Quantifying the bias in data links
 

Similar to Data Structures Trees Overview

Data structures and Algorithm analysis_Lecture4.pptx
Data structures and Algorithm analysis_Lecture4.pptxData structures and Algorithm analysis_Lecture4.pptx
Data structures and Algorithm analysis_Lecture4.pptxAhmedEldesoky24
 
CS1027-Trees-2020 lecture one .pdf
CS1027-Trees-2020 lecture one       .pdfCS1027-Trees-2020 lecture one       .pdf
CS1027-Trees-2020 lecture one .pdfAliaaTarek5
 
Farhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructureFarhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructureFarhana Shaikh
 
tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptxMouDhara1
 
data_structures_and_applications_-_module-4.ppt
data_structures_and_applications_-_module-4.pptdata_structures_and_applications_-_module-4.ppt
data_structures_and_applications_-_module-4.pptssuser5c874e
 
part4-trees.ppt
part4-trees.pptpart4-trees.ppt
part4-trees.pptSuneel61
 
ntroduction to Algorithm 2.pptx
ntroduction to Algorithm 2.pptxntroduction to Algorithm 2.pptx
ntroduction to Algorithm 2.pptxMarisse Presilda
 
Lecture 9: Binary tree basics
Lecture 9: Binary tree basicsLecture 9: Binary tree basics
Lecture 9: Binary tree basicsVivek Bhargav
 
358 33 powerpoint-slides_10-trees_chapter-10
358 33 powerpoint-slides_10-trees_chapter-10358 33 powerpoint-slides_10-trees_chapter-10
358 33 powerpoint-slides_10-trees_chapter-10sumitbardhan
 
B tree ,B plus and graph
B tree ,B plus and graph B tree ,B plus and graph
B tree ,B plus and graph RaaviKapoor
 
Tree Introduction.pptx
Tree Introduction.pptxTree Introduction.pptx
Tree Introduction.pptxRahulAI
 

Similar to Data Structures Trees Overview (20)

210 trees
210 trees210 trees
210 trees
 
210 trees5
210 trees5210 trees5
210 trees5
 
Unit III.ppt
Unit III.pptUnit III.ppt
Unit III.ppt
 
Tree 11.ppt
Tree 11.pptTree 11.ppt
Tree 11.ppt
 
Data structures and Algorithm analysis_Lecture4.pptx
Data structures and Algorithm analysis_Lecture4.pptxData structures and Algorithm analysis_Lecture4.pptx
Data structures and Algorithm analysis_Lecture4.pptx
 
CS1027-Trees-2020 lecture one .pdf
CS1027-Trees-2020 lecture one       .pdfCS1027-Trees-2020 lecture one       .pdf
CS1027-Trees-2020 lecture one .pdf
 
Farhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructureFarhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructure
 
tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptx
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 
DSA-Unit-2.pptx
DSA-Unit-2.pptxDSA-Unit-2.pptx
DSA-Unit-2.pptx
 
data_structures_and_applications_-_module-4.ppt
data_structures_and_applications_-_module-4.pptdata_structures_and_applications_-_module-4.ppt
data_structures_and_applications_-_module-4.ppt
 
Trees
TreesTrees
Trees
 
part4-trees.ppt
part4-trees.pptpart4-trees.ppt
part4-trees.ppt
 
Module 8.1 Trees.pdf
Module 8.1 Trees.pdfModule 8.1 Trees.pdf
Module 8.1 Trees.pdf
 
ntroduction to Algorithm 2.pptx
ntroduction to Algorithm 2.pptxntroduction to Algorithm 2.pptx
ntroduction to Algorithm 2.pptx
 
Lecture 9: Binary tree basics
Lecture 9: Binary tree basicsLecture 9: Binary tree basics
Lecture 9: Binary tree basics
 
358 33 powerpoint-slides_10-trees_chapter-10
358 33 powerpoint-slides_10-trees_chapter-10358 33 powerpoint-slides_10-trees_chapter-10
358 33 powerpoint-slides_10-trees_chapter-10
 
B tree ,B plus and graph
B tree ,B plus and graph B tree ,B plus and graph
B tree ,B plus and graph
 
Unit 3 trees
Unit 3   treesUnit 3   trees
Unit 3 trees
 
Tree Introduction.pptx
Tree Introduction.pptxTree Introduction.pptx
Tree Introduction.pptx
 

More from Rajendran

Element distinctness lower bounds
Element distinctness lower boundsElement distinctness lower bounds
Element distinctness lower boundsRajendran
 
Scheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsScheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsRajendran
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower boundsRajendran
 
Red black tree
Red black treeRed black tree
Red black treeRajendran
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statisticsRajendran
 
Proof master theorem
Proof master theoremProof master theorem
Proof master theoremRajendran
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree methodRajendran
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theoremRajendran
 
Master method
Master method Master method
Master method Rajendran
 
Master method theorem
Master method theoremMaster method theorem
Master method theoremRajendran
 
Master method theorem
Master method theoremMaster method theorem
Master method theoremRajendran
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithmsRajendran
 
Longest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisLongest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisRajendran
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisRajendran
 
Average case Analysis of Quicksort
Average case Analysis of QuicksortAverage case Analysis of Quicksort
Average case Analysis of QuicksortRajendran
 
Np completeness
Np completenessNp completeness
Np completenessRajendran
 
computer languages
computer languagescomputer languages
computer languagesRajendran
 

More from Rajendran (20)

Element distinctness lower bounds
Element distinctness lower boundsElement distinctness lower bounds
Element distinctness lower bounds
 
Scheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsScheduling with Startup and Holding Costs
Scheduling with Startup and Holding Costs
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower bounds
 
Red black tree
Red black treeRed black tree
Red black tree
 
Hash table
Hash tableHash table
Hash table
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statistics
 
Proof master theorem
Proof master theoremProof master theorem
Proof master theorem
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree method
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theorem
 
Master method
Master method Master method
Master method
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Hash tables
Hash tablesHash tables
Hash tables
 
Lower bound
Lower boundLower bound
Lower bound
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Longest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisLongest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm Analysis
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
 
Average case Analysis of Quicksort
Average case Analysis of QuicksortAverage case Analysis of Quicksort
Average case Analysis of Quicksort
 
Np completeness
Np completenessNp completeness
Np completeness
 
computer languages
computer languagescomputer languages
computer languages
 

Recently uploaded

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
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
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
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
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
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
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
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
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 

Recently uploaded (20)

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.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
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
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
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
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
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
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
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 

Data Structures Trees Overview

  • 2. Summary • Topics • general trees, definitions and properties • interface and implementation • tree traversal algorithms • depth and height • pre-order traversal • post-order traversal
  • 3. Trees • So far we have seen linear structures • linear: before and after relationship • lists, vectors, arrays, stacks, queues, etc • Non-linear structure: trees • probably the most fundamental structure in computing • hierarchical structure • Terminology: from family trees (genealogy)
  • 4. root Trees • store elements hierarchically • the top element: root • except the root, each element has a parent • each element has 0 or more children
  • 5. Trees • Definition • A tree T is a set of nodes storing elements such that the nodes have a parent-child relationship that satisfies the following • if T is not empty, T has a special tree called the root that has no parent • each node v of T different than the root has a unique parent node w; each node with parent w is a child of w • Recursive definition • T is either empty • or consists of a node r (the root) and a possibly empty set of trees whose roots are the children of r • Terminology • siblings: two nodes that have the same parent are called siblings • internal nodes • nodes that have children • external nodes or leaves • nodes that don’t have children • ancestors • descendants
  • 9. Application of trees • Applications of trees • class hierarchy in Java • file system • storing hierarchies in organizations
  • 10. Tree ADT • Whatever the implementation of a tree is, its interface is the following • root() • size() • isEmpty() • parent(v) • children(v) • isInternal(v) • isExternal(v) • isRoot()
  • 11. Algorithms on trees • Definition: • depth(T, v) is the number of ancestors of v, excluding v itself • //compute the depth of a node v in tree T • int depth(T, v) • recursive formulation • if v == root, then depth(v) = 0 • else, depth(v) is 1 + depth (parent(v)) • Algorithm: int depth(T,v) { if T.isRoot(v) return 0 return 1 + depth(T, T.parent(v)) } • Analysis: • O(number of ancestors) = O(depth_v) • in the worst case the path is a linked-list and v is the leaf • ==> O(n), where n is the number of nodes in the tree
  • 12. Algorithms on trees • Definition: • height of a node v in T is the length of the longest path from v to any leaf • //compute the height of tree T • int height(T,v) • recursive definition: • if v is leaf, then its height is 0 • else height(v) = 1 + maximum height of a child of v • definition: • the height of a tree is the height of its root • Proposition: the height of a tree T is the maximum depth of one of its leaves.
  • 13. Height • Algorithm: int height(T,v) { if T.isExternal(v) return 0; int h = 0; for each child w of v in T do h = max(h, height(T, w)) return h+1; } • Analysis: • total time: the sum of times spent at each node, for all nodes • the algorithm is recursive; • v calls height(w) on all children w of v • height() will eventually be called on every descendant of v • is called on each node precisely once, because each node has one parent • aside from recursion • for each node v: go through all children of v • O(1 + c_v) where c_v is the number of children of v • over all nodes: O(n) + SUM (c_v) • each node is child of only one node, so its processed once as a