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

Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 

Recently uploaded (20)

Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 

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