SlideShare a Scribd company logo
1 of 15
Download to read offline
Chapter 4: Trees (Binary)
Text: Read Weiss, §4.1 – 4.2
1
Preliminaries - I
• (Recursive) Definition: A tree is a collection
of nodes. The collection can be empty;
otherwise, a tree consists of a distinguished
node r, called the root, and zero or more
nonempty (sub)trees T1, T2, ..., Tk, each of
whose roots are connected by a directed
edge from r. The root of each subtree is
said to be a child of r, and r is the parent of
each subtree root.
2
Preliminaries - II
• Observation: For a tree with N nodes, there
are N-1 edges.
• Proof: Each edge connects a node to its
parent and every node except the root has
one parent.
3
Preliminaries - III
• The root is A. Node F has A as a parent and K, L,
and M as children. Each node may have an
arbitrary number of children, possibly zero. Nodes
with no children are known as leaves (leaf node).
B, C, H, I, P, Q, K, L, M, and N are leaves. Nodes
with the same parent are siblings; thus K, L, and
M are all siblings. Grandparent and grandchild
relations can be defined in a similar manner.
4
Preliminaries - IV
• A path from node n1 to nk is defined as a sequence of
nodes n1, n2, ..., nk such that ni is the parent of ni+1 for 1 ≤ i <
k. The length of this path is the number of edges on the
path, namely k - 1. There is a path of length zero from every
node to itself. Notice that there is exactly one path from the
root to each node.
• For any node ni, the depth of ni is the length of the unique
path from the root to ni. Thus, the root is at depth 0. The
height of ni is the length of the longest path from ni to a leaf.
Thus all leaves are at height 0. The height of a tree is equal
to the height of the root. The depth of a tree is equal to the
depth of the deepest leaf which is always equal to the height
of the tree. If there is path from n1 to n2 (n1≠n2), then n1 is an
(proper) ancestor of n2 and n2 is a (proper) descendant of
n1.
5
Implementation of Trees
• One way is to have in each node besides its data,
a link to to each child of that node. However, since
the number of children per node can vary greatly
and is not known in advance, it might be infeasible.
The solution is simple: keep the children in a linked
list of tree nodes.
6
Tree Traversals with an Application - I
• One popular use is the directory structure in many common
operating systems.
• The root of this directory is /usr. (The asterisk next to the
name indicates that /usr is itself a directory.) /usr has three
children, mark, alex, and bill, which are themselves
directories. Thus, /usr contains three directories and no
regular files. The filename /usr/mark/book/ch1.r is obtained
by following the leftmost child three times. Each / after the
first indicates an edge; the result is the full pathname.
7
• Suppose we would like to list the names of all of the files in the
directory. Our output format will be that files that are at depth d will
have their names indented by d tabs. The strategy below is known as
preorder traversal. In a preorder traversal, work at a node is
performed before (pre) its children. If there are N file names, then the
running time is O(N).
8
Tree Traversals with an Application - II
void list_directory (DirEntry* D){
listAll ( D, 0 );
}
void listAll (DirEntry* D, unsigned int depth){
if ( D != NULL){
printName ( depth, D->name );
if( isDirectory(D))
for each child c of D
listAll ( c, depth+1 );
}
}
• Another common method of traversing a tree is the postorder traversal.
With it, the work at a node is performed after (post) its children are
evaluated. As an example, the same directory structure as before, is
represented with the numbers in parentheses (the number of disk blocks
taken up by each file). Since the directories are themselves files, they have
size too. The running time of calculating the size each node is O(N) again.
9
Tree Traversals with an Application - III
unsigned int size(DirEntry* D){
unsigned int totalSize = 0;
if(D != NULL){
totalSize=sizeOfThisFile(D);
if( isDirectory(D) )
for each child c of D
totalSize += size( c );
}
return( totalSize );
}
Binary Trees
• A binary tree is a tree in which no node can have more
than two children. Subtrees TL and TR which could both be
possibly empty. The depth of an average binary tree is
considerably smaller than N ( actually O( ) ). For a
special type of binary tree, namely the binary search tree,
the average value of depth is O (log N). Unfortunately it can
be as large as N - 1.
10
N
Implementation
11
typedef struct tree_node *tree_ptr;
struct tree_node
{
element_type element;
tree_ptr left;
tree_ptr right;
};
typedef tree_ptr TREE;
• Because a binary tree has at most two children, we
can keep direct links to them. The declaration of tree
nodes is similar in structure to that for doubly linked
lists, in that a node is a structure consisting of the
element information plus two pointers (left and right) to
other nodes.
• Trees are generally drawn as circles connected by
lines. NULL links are not explicitly drawn.
• Why? A binary tree with N
nodes, has N+1 NULL links.
• Proof: Ni: #nodes with i children
N0+N1+N2=N (1) // #nodes
N1+2*N2=N-1 (2) // #edges
multiply (1) by 2 and subtract (2)
2*N0+N1=2*N-(N-1)=N+1
12
An Example: Expression Trees
• The leaves of an expression tree are operands, such as
constants or variable names, and the other nodes contain
operators. Operator nodes might have 1 (unary minus), 2,
or more than two children. We can evaluate an expression
tree, T, by applying the operator at the root to the values
obtained by recursively evaluating the left and right subtrees.
• Inorder traversal: produce an infix expression by first
recursively processing left, then, output the operator at the
root, and finally recursively process the right.
•the left subtree evaluates to
a + (b * c) and
•the right subtree evaluates to
((d *e) + f )*g.
•The entire tree therefore represents
(a + (b*c)) + (((d * e) + f)* g).
• We now give an algorithm to convert a postfix
expression into an expression tree. Since we
already have an algorithm to convert infix to postfix,
we can generate expression trees from the two
common types of input. The method we describe
strongly resembles the postfix evaluation algorithm
of Section 3.2.3.
Constructing an Expression Tree - I
13
stack=∅;
while (!EndOf(expression)){
read(ch);
if (isOperand(ch))
push(MakeNode(ch, NULL, NULL), stack);
else if (isOperator(ch)){
T1=topAndPop(stack);
T2=topAndPop(stack);
push(MakeNode(ch, T2, T1), stack);
}
}
MakeNode(data,left,right)
creates a struct
tree_node and returns a
pointer to it
14
Constructing an Expression Tree - II
As an example, suppose the input is: a b + c d e + * *
a b + c d e + * * a b + c d e + * *
a b + c d e + * *
a b + c d e + * *
15
Constructing an Expression Tree - III
a b + c d e + * *
a b + c d e + * *

More Related Content

What's hot (20)

Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal Khan
 
Binary trees
Binary treesBinary trees
Binary trees
 
Binary tree
Binary tree Binary tree
Binary tree
 
Binary tree
Binary  treeBinary  tree
Binary tree
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
 
Tree
TreeTree
Tree
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
Cinterviews Binarysearch Tree
Cinterviews Binarysearch TreeCinterviews Binarysearch Tree
Cinterviews Binarysearch Tree
 
binary tree
binary treebinary tree
binary tree
 
Search tree,Tree and binary tree and heap tree
Search tree,Tree  and binary tree and heap treeSearch tree,Tree  and binary tree and heap tree
Search tree,Tree and binary tree and heap tree
 
Data Structure (Tree)
Data Structure (Tree)Data Structure (Tree)
Data Structure (Tree)
 
Lecture7 data structure(tree)
Lecture7 data structure(tree)Lecture7 data structure(tree)
Lecture7 data structure(tree)
 
Binary Tree Traversal
Binary Tree TraversalBinary Tree Traversal
Binary Tree Traversal
 
Lecture 5 trees
Lecture 5 treesLecture 5 trees
Lecture 5 trees
 
Data Structures 5
Data Structures 5Data Structures 5
Data Structures 5
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
 
Data structure tree- advance
Data structure tree- advanceData structure tree- advance
Data structure tree- advance
 

Similar to 7 chapter4 trees_binary

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
 
Lecture 5 tree.pptx
Lecture 5 tree.pptxLecture 5 tree.pptx
Lecture 5 tree.pptxAbirami A
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures treemaamir farooq
 
Chapter 5_Trees.pdf
Chapter 5_Trees.pdfChapter 5_Trees.pdf
Chapter 5_Trees.pdfssuser50179b
 
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
 
Trees and Graphs in data structures and Algorithms
Trees and Graphs in data structures and AlgorithmsTrees and Graphs in data structures and Algorithms
Trees and Graphs in data structures and AlgorithmsBHARATH KUMAR
 
Farhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructureFarhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructureFarhana Shaikh
 
trees in data structure
trees in data structure trees in data structure
trees in data structure shameen khan
 
Lecture 21_Trees - I.pptx
Lecture 21_Trees - I.pptxLecture 21_Trees - I.pptx
Lecture 21_Trees - I.pptxfizzaahmed9
 
Review session2
Review session2Review session2
Review session2NEEDY12345
 

Similar to 7 chapter4 trees_binary (20)

Unit 3,4.docx
Unit 3,4.docxUnit 3,4.docx
Unit 3,4.docx
 
Unit II,III - Data Structures.pdf
Unit II,III - Data Structures.pdfUnit II,III - Data Structures.pdf
Unit II,III - Data Structures.pdf
 
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
 
Lecture 5 tree.pptx
Lecture 5 tree.pptxLecture 5 tree.pptx
Lecture 5 tree.pptx
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 
7.tree
7.tree7.tree
7.tree
 
tree.ppt
tree.ppttree.ppt
tree.ppt
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures tree
 
Dsc++ unit 3 notes
Dsc++ unit 3 notesDsc++ unit 3 notes
Dsc++ unit 3 notes
 
Chapter 5_Trees.pdf
Chapter 5_Trees.pdfChapter 5_Trees.pdf
Chapter 5_Trees.pdf
 
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 and Graphs in data structures and Algorithms
Trees and Graphs in data structures and AlgorithmsTrees and Graphs in data structures and Algorithms
Trees and Graphs in data structures and Algorithms
 
Chapter 8 ds
Chapter 8 dsChapter 8 ds
Chapter 8 ds
 
Farhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructureFarhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructure
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
binary tree.pptx
binary tree.pptxbinary tree.pptx
binary tree.pptx
 
Lecture 21_Trees - I.pptx
Lecture 21_Trees - I.pptxLecture 21_Trees - I.pptx
Lecture 21_Trees - I.pptx
 
Chap 5 Tree.ppt
Chap 5 Tree.pptChap 5 Tree.ppt
Chap 5 Tree.ppt
 
Unit 6 tree
Unit   6 treeUnit   6 tree
Unit 6 tree
 
Review session2
Review session2Review session2
Review session2
 

More from SSE_AndyLi

Chapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic CircuitsChapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic CircuitsSSE_AndyLi
 
Chapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic FunctionsChapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic FunctionsSSE_AndyLi
 
Chapter 5 introduction to VHDL
Chapter 5 introduction to VHDLChapter 5 introduction to VHDL
Chapter 5 introduction to VHDLSSE_AndyLi
 
Chapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational LogicChapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational LogicSSE_AndyLi
 
Chapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and GatesChapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and GatesSSE_AndyLi
 
Chapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital SystemsChapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital SystemsSSE_AndyLi
 
15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mst15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mstSSE_AndyLi
 
14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpathSSE_AndyLi
 
10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queuesSSE_AndyLi
 
9 chapter4 trees_avl
9 chapter4 trees_avl9 chapter4 trees_avl
9 chapter4 trees_avlSSE_AndyLi
 
8 chapter4 trees_bst
8 chapter4 trees_bst8 chapter4 trees_bst
8 chapter4 trees_bstSSE_AndyLi
 
6 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart36 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart3SSE_AndyLi
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2SSE_AndyLi
 
4 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart14 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart1SSE_AndyLi
 
3 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart23 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart2SSE_AndyLi
 
2 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart12 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart1SSE_AndyLi
 
1 chapter1 introduction
1 chapter1 introduction1 chapter1 introduction
1 chapter1 introductionSSE_AndyLi
 

More from SSE_AndyLi (17)

Chapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic CircuitsChapter 07 Digital Alrithmetic and Arithmetic Circuits
Chapter 07 Digital Alrithmetic and Arithmetic Circuits
 
Chapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic FunctionsChapter 06 Combinational Logic Functions
Chapter 06 Combinational Logic Functions
 
Chapter 5 introduction to VHDL
Chapter 5 introduction to VHDLChapter 5 introduction to VHDL
Chapter 5 introduction to VHDL
 
Chapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational LogicChapter 03 Boolean Algebra and Combinational Logic
Chapter 03 Boolean Algebra and Combinational Logic
 
Chapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and GatesChapter 02 Logic Functions and Gates
Chapter 02 Logic Functions and Gates
 
Chapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital SystemsChapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital Systems
 
15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mst15 chapter9 graph_algorithms_mst
15 chapter9 graph_algorithms_mst
 
14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath
 
10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues
 
9 chapter4 trees_avl
9 chapter4 trees_avl9 chapter4 trees_avl
9 chapter4 trees_avl
 
8 chapter4 trees_bst
8 chapter4 trees_bst8 chapter4 trees_bst
8 chapter4 trees_bst
 
6 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart36 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart3
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2
 
4 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart14 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart1
 
3 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart23 chapter2 algorithm_analysispart2
3 chapter2 algorithm_analysispart2
 
2 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart12 chapter2 algorithm_analysispart1
2 chapter2 algorithm_analysispart1
 
1 chapter1 introduction
1 chapter1 introduction1 chapter1 introduction
1 chapter1 introduction
 

Recently uploaded

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 

Recently uploaded (20)

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 

7 chapter4 trees_binary

  • 1. Chapter 4: Trees (Binary) Text: Read Weiss, §4.1 – 4.2 1
  • 2. Preliminaries - I • (Recursive) Definition: A tree is a collection of nodes. The collection can be empty; otherwise, a tree consists of a distinguished node r, called the root, and zero or more nonempty (sub)trees T1, T2, ..., Tk, each of whose roots are connected by a directed edge from r. The root of each subtree is said to be a child of r, and r is the parent of each subtree root. 2
  • 3. Preliminaries - II • Observation: For a tree with N nodes, there are N-1 edges. • Proof: Each edge connects a node to its parent and every node except the root has one parent. 3
  • 4. Preliminaries - III • The root is A. Node F has A as a parent and K, L, and M as children. Each node may have an arbitrary number of children, possibly zero. Nodes with no children are known as leaves (leaf node). B, C, H, I, P, Q, K, L, M, and N are leaves. Nodes with the same parent are siblings; thus K, L, and M are all siblings. Grandparent and grandchild relations can be defined in a similar manner. 4
  • 5. Preliminaries - IV • A path from node n1 to nk is defined as a sequence of nodes n1, n2, ..., nk such that ni is the parent of ni+1 for 1 ≤ i < k. The length of this path is the number of edges on the path, namely k - 1. There is a path of length zero from every node to itself. Notice that there is exactly one path from the root to each node. • For any node ni, the depth of ni is the length of the unique path from the root to ni. Thus, the root is at depth 0. The height of ni is the length of the longest path from ni to a leaf. Thus all leaves are at height 0. The height of a tree is equal to the height of the root. The depth of a tree is equal to the depth of the deepest leaf which is always equal to the height of the tree. If there is path from n1 to n2 (n1≠n2), then n1 is an (proper) ancestor of n2 and n2 is a (proper) descendant of n1. 5
  • 6. Implementation of Trees • One way is to have in each node besides its data, a link to to each child of that node. However, since the number of children per node can vary greatly and is not known in advance, it might be infeasible. The solution is simple: keep the children in a linked list of tree nodes. 6
  • 7. Tree Traversals with an Application - I • One popular use is the directory structure in many common operating systems. • The root of this directory is /usr. (The asterisk next to the name indicates that /usr is itself a directory.) /usr has three children, mark, alex, and bill, which are themselves directories. Thus, /usr contains three directories and no regular files. The filename /usr/mark/book/ch1.r is obtained by following the leftmost child three times. Each / after the first indicates an edge; the result is the full pathname. 7
  • 8. • Suppose we would like to list the names of all of the files in the directory. Our output format will be that files that are at depth d will have their names indented by d tabs. The strategy below is known as preorder traversal. In a preorder traversal, work at a node is performed before (pre) its children. If there are N file names, then the running time is O(N). 8 Tree Traversals with an Application - II void list_directory (DirEntry* D){ listAll ( D, 0 ); } void listAll (DirEntry* D, unsigned int depth){ if ( D != NULL){ printName ( depth, D->name ); if( isDirectory(D)) for each child c of D listAll ( c, depth+1 ); } }
  • 9. • Another common method of traversing a tree is the postorder traversal. With it, the work at a node is performed after (post) its children are evaluated. As an example, the same directory structure as before, is represented with the numbers in parentheses (the number of disk blocks taken up by each file). Since the directories are themselves files, they have size too. The running time of calculating the size each node is O(N) again. 9 Tree Traversals with an Application - III unsigned int size(DirEntry* D){ unsigned int totalSize = 0; if(D != NULL){ totalSize=sizeOfThisFile(D); if( isDirectory(D) ) for each child c of D totalSize += size( c ); } return( totalSize ); }
  • 10. Binary Trees • A binary tree is a tree in which no node can have more than two children. Subtrees TL and TR which could both be possibly empty. The depth of an average binary tree is considerably smaller than N ( actually O( ) ). For a special type of binary tree, namely the binary search tree, the average value of depth is O (log N). Unfortunately it can be as large as N - 1. 10 N
  • 11. Implementation 11 typedef struct tree_node *tree_ptr; struct tree_node { element_type element; tree_ptr left; tree_ptr right; }; typedef tree_ptr TREE; • Because a binary tree has at most two children, we can keep direct links to them. The declaration of tree nodes is similar in structure to that for doubly linked lists, in that a node is a structure consisting of the element information plus two pointers (left and right) to other nodes. • Trees are generally drawn as circles connected by lines. NULL links are not explicitly drawn. • Why? A binary tree with N nodes, has N+1 NULL links. • Proof: Ni: #nodes with i children N0+N1+N2=N (1) // #nodes N1+2*N2=N-1 (2) // #edges multiply (1) by 2 and subtract (2) 2*N0+N1=2*N-(N-1)=N+1
  • 12. 12 An Example: Expression Trees • The leaves of an expression tree are operands, such as constants or variable names, and the other nodes contain operators. Operator nodes might have 1 (unary minus), 2, or more than two children. We can evaluate an expression tree, T, by applying the operator at the root to the values obtained by recursively evaluating the left and right subtrees. • Inorder traversal: produce an infix expression by first recursively processing left, then, output the operator at the root, and finally recursively process the right. •the left subtree evaluates to a + (b * c) and •the right subtree evaluates to ((d *e) + f )*g. •The entire tree therefore represents (a + (b*c)) + (((d * e) + f)* g).
  • 13. • We now give an algorithm to convert a postfix expression into an expression tree. Since we already have an algorithm to convert infix to postfix, we can generate expression trees from the two common types of input. The method we describe strongly resembles the postfix evaluation algorithm of Section 3.2.3. Constructing an Expression Tree - I 13 stack=∅; while (!EndOf(expression)){ read(ch); if (isOperand(ch)) push(MakeNode(ch, NULL, NULL), stack); else if (isOperator(ch)){ T1=topAndPop(stack); T2=topAndPop(stack); push(MakeNode(ch, T2, T1), stack); } } MakeNode(data,left,right) creates a struct tree_node and returns a pointer to it
  • 14. 14 Constructing an Expression Tree - II As an example, suppose the input is: a b + c d e + * * a b + c d e + * * a b + c d e + * * a b + c d e + * * a b + c d e + * *
  • 15. 15 Constructing an Expression Tree - III a b + c d e + * * a b + c d e + * *