SlideShare una empresa de Scribd logo
1 de 74
UNIT III
The Tree ADT
Topics to be covered
• Tree ADT – tree traversals – Binary Tree ADT –
expression trees – applications of trees – binary search
tree ADT –Threaded Binary Trees- AVL Trees – B-Tree
– B+ Tree – Heap – Applications of heap.
Trees
• A tree is a nonlinear abstract data type that
stores elements in a hierarchy.
• Examples in real life:
• Family tree
• Table of contents of a book
• Class inheritance hierarchy in Java
• Computer file system (folders and subfolders)
• Decision trees
Example: Computer File System
Root directory of C drive
Documents and Settings Program Files My Music
Desktop Favorites Start Menu Microsoft Office
Adobe
Tree Definition
• Tree: a set of elements that either
• it is empty
• or, it has a distinguished element called
the root and zero or more trees (called
subtrees of the root)
Tree Definition
Subtrees of
the root
Root
Tree Terminology
• Nodes: the elements in the tree
• Edges: connections between nodes
• Root: the distinguished element that is the
origin of the tree
• There is only one root node in a tree
• Empty tree has no nodes and no edges
Tree Terminology
nodes
Root
edges
• Parent or predecessor: the node directly above
another node in the hierarchy
• A node can have only one parent
• Child or successor: a node directly below
another node in the hierarchy
• Siblings: nodes that have the same parent
• Ancestors of a node: its parent, the parent of its
parent, etc.
• Descendants of a node: its children, the children
of its children, etc.
Tree Terminology
Tree Terminology
• Leaf node: a node without children
• Internal node: a node that is not a leaf node
Tree Terminology
Leaf
nodes
Root
Interior or
internal
nodes
Discussion
• Does a leaf node have any children?
• Does the root node have a parent?
• How many parents does every node
other than the root node have?
Height of a Tree
• A path is a sequence of edges leading
from one node to another
• Length of a path: number of edges
on the path
• Height of a (non-empty) tree : length
of the longest path from the root to a
leaf
• What is the height of a tree that has only a
root node?
• By convention, the height of an empty
tree is -1
Level of a Node
• Level of a node: number of edges
between root and the node
• It can be defined recursively:
• Level of root node is 0
• Level of a node that is not the root node is
level of its parent + 1
• Question: What is the level of a node
in terms of path length?
• Question: What is the height of a tree
in terms of levels?
Level of a Node
Level 0
Level 1
Level 2
Level 3
Subtrees
• Subtree of a node: consists of a
child node and all its descendants
• A subtree is itself a tree
• A node may have many subtrees
Subtrees
Subtrees of the
node labeled E
E
More Tree Terminology
• Degree or arity of a node: the number of
children it has
• Degree or arity of a tree: the maximum
of the degrees of the tree’s nodes
Questions
• Level order traversal of a rooted tree can be done by
starting from the root and performing
• preorder traversal
• in-order traversal
• depth first search
• breadth first search
Binary Trees
• General tree: a tree each of whose
nodes may have any number of children
• n-ary tree: a tree each of whose nodes
may have no more than n children
• Binary tree: a tree each of whose nodes
may have no more than 2 children
• i.e. a binary tree is a tree with degree
(arity) 2
• The children (if present) are called the
left child and right child
• Recursive definition of a binary tree:
it is
• The empty tree
• Or, a tree which has a root whose left and
right subtrees are binary trees
• A binary tree is a positional tree, i.e. it
matters whether the subtree is left or
right
Binary Trees
Binary Tree
A
I
H
D E
B
F
C
G
Tree Traversals
• A traversal of a tree requires that each
node of the tree be visited once
• Example: a typical reason to traverse a
tree is to display the data stored at each
node of the tree
• Standard traversal orderings:
• preorder
• inorder
• postorder
• level-order
Traversals
We’ll trace the different traversals using this tree; recursive calls,
returns, and “visits” will be numbered in the order they occur
A
I
H
D E
B
F
C
G
Preorder Traversal
• Start at the root
• Visit each node, followed by its children; we will
choose to visit left child before right
• Recursive algorithm for preorder traversal:
• If tree is not empty,
• Visit root node of tree
• Perform preorder traversal of its left subtree
• Perform preorder traversal of its right
subtree
Preorder Traversal
1: visit A
29: visit I
9: visit H
5: visit D 17: visit E
3: visit B
27: visit F
25: visit C
39:
visit G
Nodes are visited in the order ABDHECFIG
. .
.
.
. .
. .
.
6
4
2
11
10
8
7
16
15
14
13
12
21
20
19
18 28
26
24
23
22
34
33
32
31
30
38
37
45
44
43
42
41
40
35
36
Inorder Traversal
• Start at the root
• Visit the left child of each node, then the node,
then any remaining nodes
• Recursive algorithm for inorder traversal
• If tree is not empty,
• Perform inorder traversal of left subtree of root
• Visit root node of tree
• Perform inorder traversal of its right subtree
Inorder Traversal
23: visit A
29: visit I
9: visit H
5: visit D 18: visit E
14: visit B
33: visit F
37: visit C
41:
visit G
Nodes are visited in the order DHBEAIFCG
. .
.
.
. .
. .
.
3
2
1
8
7
6
4
15
13
12
11
10
20
19
17
16 26
25
24
22
21
32
31
30
28
27
38
36
45
44
43
42
40
39
34
35
Postorder Traversal
• Start at the root
• Visit the children of each node, then the node
• Recursive algorithm for postorder traversal
• If tree is not empty,
• Perform postorder traversal of left subtree of root
• Perform postorder traversal of right subtree of root
• Visit root node of tree
Postorder Traversal
45: visit A
30: visit I
10: visit H
12: visit D 19: visit E
21: visit B
34: visit F
43: visit C
41:
visit G
Nodes are visited in the order HDEBIFGCA
. .
.
.
. .
. .
.
3
2
1
7
6
5
4
14
13
11
9
8
18
17
16
15 25
24
23
22
20
31
29
28
27
26
36
35
44
42
40
39
38
37
32
33
Things to Note
• Note that the relative order of the
recursive calls in preorder, inorder and
post order traversals is the same
• The only differences stem from where
the visiting of the root node of a subtree
actually takes place
Level Order Traversal
• Start at the root
• Visit the nodes at each level, from left to
right
• Is there a recursive algorithm for a level
order traversal?
Level Order Traversal
A
I
H
D E
B
F
C
G
Nodes will be visited in the order ABCDEFGHI
Iterative Binary Tree Traversals
• In recursive tree traversals, the Java call stack
keeps track of where we are in the tree (by
means of the call frames for each call)
• In iterative traversals, the programmer needs
to keep track!
• An iterative traversal uses a container to store
references to nodes not yet visited
• Order of visiting will depend on the type of container
being used (stack, queue, etc.)
10-40
An Iterative Traversal Algorithm
// Assumption: the tree is not empty
Create an empty container to hold references to nodes
yet to be visited.
Put reference to the root node in the container.
While the container is not empty {
Remove a reference x from the container.
Visit the node x points to.
Put references to non-empty children of x in the container.
}
}
10-41
• Container is a stack: if we push the right
successor of a node before the left successor,
we get preorder traversal
• Container is a queue: if we enqueue the left
successor before the right, we get a level order
traversal
• Exercise: Trace the iterative tree traversal
algorithm using as containers
• a stack
• a queue
Iterative Binary Tree Traversals
10-42
Traversal Analysis
• Consider a binary tree with n nodes
• How many recursive calls are there at
most?
• For each node, 2 recursive calls at
most
• So, 2*n recursive calls at most
• So, a traversal is O(n)
10-43
Operations on a Binary Tree
• What might we want to do with a binary
tree?
• Add an element (but where?)
• Remove an element (but from where?)
• Is the tree empty?
• Get size of the tree (i.e. how many
elements)
• Traverse the tree (in preorder, inorder,
postorder, level order)
10-44
Discussion
• It is difficult to have a general add
operation, until we know the purpose of
the tree (we will discuss binary search
trees later)
• We could add “randomly”: go either right
or left, and add at the first available spot
10-45
Discussion
• Similarly, where would a general
remove operation remove from?
• We could arbitrarily choose to remove, say,
the leftmost leaf
• If random choice, what would happen to
the children and descendants of the
element that was removed? What does the
parent of the removed element now point
to?
• What if the removed element is the root?
10-46
Possible Binary Tree Operations
Operation Description
removeLeftSubtree Removes the left subtree of the root
removeRightSubtree Removes the right subtree of the root
removeAllElements Removes all elements from the tree
isEmpty Determines whether the tree is empty
size Determines the number of elements in the tree
contains Determines if a particular element is in the tree
find Returns a reference to the specified target, if found
toString Returns a string representation of tree’s contents
iteratorInOrder Returns an iterator for an inorder traversal
iteratorPreOrder Returns an iterator for a preorder traversal
iteratorPostOrder Returns an iterator for a postorder traversal
iteratorLevelOrder Returns an iterator for a levelorder traversal
10-47
Binary Tree Operations
• Our textbook has a smaller set of
operations for the BinaryTreeADT
• See BinaryTreeADT.java
10-48
Linked Binary Tree Implementation
• To represent the binary tree, we will use a
linked structure of nodes
• root: reference to the node that is the root
of the tree
• count: keeps track of the number of nodes
in the tree
• First, how will we represent a node of a
binary tree?
10-49
Binary Tree Node
• A binary tree node will contain
• a reference to a data element
• references to its left and right children
left and right children are binary tree nodes themselves
10-50
BinaryTreeNode class
• Represents a node in a binary tree
• Attributes:
• element: reference to data element
• left: reference to left child of the node
• right: reference to right child of the node
• See BinaryTreeNode.java
• Note that the attributes here are protected
• This means that they can be accessed directly from
any class that is in the same package as
BinaryTreeNode.java
10-51
A BinaryTreeNode Object
protected T element;
protected BinaryTreeNode<T> left, right;
element
data object
left right
Note that either or both of the left and right references could be null
10-52
LinkedBinaryTree Class
• Attributes:
protected BinaryTreeNode<T> root;
protected int count;
• The attributes are protected so that they can
be accessed directly in any subclass of the
LinkedBinaryTree class
• We will be looking at a very useful kind of
binary tree called a Binary Search Tree
later
10-53
LinkedBinaryTree Class
• Constructors:
//Creates empty binary tree
public LinkedBinaryTree() {
count = 0;
root = null;
}
//Creates binary tree with specified element as its root
public LinkedBinaryTree (T element) {
count = 1;
root = new BinaryTreeNode<T> (element);
}
10-54
/* Returns a reference to the specified target element if it is
found in this binary tree.
Throws an ElementNotFoundException if not found. */
public T find(T targetElement) throws
ElementNotFoundException
{
BinaryTreeNode<T> current =
findAgain( targetElement, root );
if ( current == null )
throw new ElementNotFoundException("binary tree");
return (current.element);
} find method
10-55
Discussion
• What is element in this statement from
the method?
return (current.element);
• If element were private rather than
protected in BinaryTreeNode.java, what
would be need in order to access it?
• We will now look at the helper method
findAgain …
10-56
private BinaryTreeNode<T> findAgain(T targetElement,
BinaryTreeNode<T> next)
{
if (next == null)
return null;
if (next.element.equals(targetElement))
return next;
BinaryTreeNode<T> temp =
findAgain(targetElement, next.left);
if (temp == null)
temp = findAgain(targetElement, next.right);
return temp;
} findAgain helper method
10-57
Discussion
• What kind of method is findAgain?
• What is the base case?
• There are two!
• What is the recursive part?
10-58
/* Performs an inorder traversal on this binary tree by
calling a recursive inorder method that starts with
the root.
Returns an inorder iterator over this binary tree */
public Iterator<T> iteratorInOrder()
{
ArrayUnorderedList<T> tempList =
new ArrayUnorderedList<T>();
inorder (root, tempList);
return tempList.iterator();
}
iteratorInOrder method
10-59
Discussion
• iteratorInOrder is returning an iterator
object
• It will perform the iteration in inorder
• But where is that iterator coming from?
return tempList.iterator();
• Let’s now look at the helper method
inorder …
10-60
/* Performs a recursive inorder traversal.
Parameters are: the node to be used as the root
for this traversal, the temporary list for use in this
traversal */
protected void inorder (BinaryTreeNode<T> node,
ArrayUnorderedList<T> tempList)
{
if (node != null)
{
inorder (node.left, tempList);
tempList.addToRear(node.element);
inorder (node.right, tempList);
}
}
inorder helper method
10-61
Discussion
• Recall the recursive algorithm for inorder
traversal:
• If tree is not empty,
• Perform inorder traversal of left subtree of
root
• Visit root node of tree
• Perform inorder traversal of its right subtree
• That’s exactly the order that is being
implemented here!
• What is “visiting” the root node here?
10-62
Discussion
• The data elements of the tree (i.e. items
of type T) are being temporarily added
to an unordered list, in inorder order
• Why use an unordered list??
• Why not? We already have this
collection, with its iterator operation
that we can use!
10-63
Using Binary Trees: Expression Trees
• Programs that manipulate or evaluate
arithmetic expressions can use binary
trees to hold the expressions
• An expression tree represents an
arithmetic expression such as
(5 – 3) * 4 + 9 / 2
• Root node and interior nodes contain
operations
• Leaf nodes contain operands
10-64
Example: An Expression Tree
/
-
3
5
+
(5 – 3) * 4 + 9 / 2
4
*
9 2
10-65
Evaluating Expression Trees
• We can use an expression tree to evaluate
an expression
• We start the evaluation at the bottom left
• What kind of traversal is this?
10-66
Evaluating an Expression Tree
-
5
7 8
/
2
9
* This tree represents
the expression
(9 / 2 + 7) * (8 – 5)
Evaluation is based on postorder traversal:
If root node is a leaf, return the associated value.
Recursively evaluate expression in left subtree.
Recursively evaluate expression in right subtree.
Perform operation in root node on these two
values, and return result.
+
10-67
Building an Expression Tree
• Now we know how to evaluate an
expression represented by an expression
tree
• But, how do we build an expression tree?
• We will build it from the postfix form of
the expression
• Exercise: develop the algorithm by
following the diagrams on the next pages
10-68
Building an Expression Tree
• The algorithm will use a stack of
ExpressionTree objects
• An ExpressionTree is a special case of a
binary tree
• The ExpressionTree constructor has 3
parameters:
• Reference to data item
• Reference to left child
• Reference to right child
• That's all you need to know to develop the
algorithm!
10-69
Build an expression tree from the postfix
expression 5 3 - 4 * 9 +
Token
5 push(new ExpressionTree(5,null,null));
Processing Step(s)
Expression Tree Stack (top at right)
5
Token
3
push(new ExpressionTree(3,null,null));
Processing Step(s)
Expression Tree Stack (top at right)
5 3
10-70
Token
-
op2 = pop
op1 = pop
push(new ExpressionTree(-,op1,op2));
Processing Step(s)
Expression Tree Stack (top at right)
5
-
3
10-71
Token
4
push(new ExpressionTree(4,null,null));
Processing Step(s)
Expression Tree Stack (top at right)
5
-
3
4
10-72
Token
*
op2 = pop
op1 = pop
push(new ExpressionTree(*,op1,op2));
Processing Step(s)
Expression Tree Stack (top at right)
5
-
3
4
*
10-73
Token
9
push(new ExpressionTree(9,null,null));
Processing Step(s)
Expression Tree Stack (top at right)
5
-
3
4
* 9
10-74
Token
+
op2 = pop
op1 = pop
push(new ExpressionTree(+,op1,op2));
Processing Step(s)
Expression Tree Stack (top at right)
5
-
3
4
* 9
+
End of the expression
has been reached, and
the full expression tree
is the only tree left on
the stack

Más contenido relacionado

Similar a Unit III.ppt

Similar a Unit III.ppt (20)

Data structure(Part 2)
Data structure(Part 2)Data structure(Part 2)
Data structure(Part 2)
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 
Binary tree
Binary treeBinary tree
Binary tree
 
Trees
TreesTrees
Trees
 
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
 
TERMINOLOGIES OF TREE, TYPES OF TREE.pptx
TERMINOLOGIES OF TREE, TYPES OF TREE.pptxTERMINOLOGIES OF TREE, TYPES OF TREE.pptx
TERMINOLOGIES OF TREE, TYPES OF TREE.pptx
 
Tree
TreeTree
Tree
 
Module - 5_Trees.pdf
Module - 5_Trees.pdfModule - 5_Trees.pdf
Module - 5_Trees.pdf
 
Introduction to tree ds
Introduction to tree dsIntroduction to tree ds
Introduction to tree ds
 
Binary tree traversal ppt - 02.03.2020
Binary tree traversal   ppt - 02.03.2020Binary tree traversal   ppt - 02.03.2020
Binary tree traversal ppt - 02.03.2020
 
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
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
unit 4 for trees data structure notes it is
unit 4 for trees data structure notes it isunit 4 for trees data structure notes it is
unit 4 for trees data structure notes it is
 
Basic of trees 2
Basic of trees 2Basic of trees 2
Basic of trees 2
 
Tree Basic concepts of Tree in Data Structure
Tree Basic concepts of Tree in Data StructureTree Basic concepts of Tree in Data Structure
Tree Basic concepts of Tree in Data Structure
 
Tree
TreeTree
Tree
 
Farhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructureFarhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructure
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Trees
TreesTrees
Trees
 

Último

Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
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
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxleah joy valeriano
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 

Último (20)

Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
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
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 

Unit III.ppt

  • 2. Topics to be covered • Tree ADT – tree traversals – Binary Tree ADT – expression trees – applications of trees – binary search tree ADT –Threaded Binary Trees- AVL Trees – B-Tree – B+ Tree – Heap – Applications of heap.
  • 3. Trees • A tree is a nonlinear abstract data type that stores elements in a hierarchy. • Examples in real life: • Family tree • Table of contents of a book • Class inheritance hierarchy in Java • Computer file system (folders and subfolders) • Decision trees
  • 4. Example: Computer File System Root directory of C drive Documents and Settings Program Files My Music Desktop Favorites Start Menu Microsoft Office Adobe
  • 5. Tree Definition • Tree: a set of elements that either • it is empty • or, it has a distinguished element called the root and zero or more trees (called subtrees of the root)
  • 7. Tree Terminology • Nodes: the elements in the tree • Edges: connections between nodes • Root: the distinguished element that is the origin of the tree • There is only one root node in a tree • Empty tree has no nodes and no edges
  • 9. • Parent or predecessor: the node directly above another node in the hierarchy • A node can have only one parent • Child or successor: a node directly below another node in the hierarchy • Siblings: nodes that have the same parent • Ancestors of a node: its parent, the parent of its parent, etc. • Descendants of a node: its children, the children of its children, etc. Tree Terminology
  • 10. Tree Terminology • Leaf node: a node without children • Internal node: a node that is not a leaf node
  • 12. Discussion • Does a leaf node have any children? • Does the root node have a parent? • How many parents does every node other than the root node have?
  • 13. Height of a Tree • A path is a sequence of edges leading from one node to another • Length of a path: number of edges on the path • Height of a (non-empty) tree : length of the longest path from the root to a leaf • What is the height of a tree that has only a root node? • By convention, the height of an empty tree is -1
  • 14. Level of a Node • Level of a node: number of edges between root and the node • It can be defined recursively: • Level of root node is 0 • Level of a node that is not the root node is level of its parent + 1 • Question: What is the level of a node in terms of path length? • Question: What is the height of a tree in terms of levels?
  • 15. Level of a Node Level 0 Level 1 Level 2 Level 3
  • 16. Subtrees • Subtree of a node: consists of a child node and all its descendants • A subtree is itself a tree • A node may have many subtrees
  • 18. More Tree Terminology • Degree or arity of a node: the number of children it has • Degree or arity of a tree: the maximum of the degrees of the tree’s nodes
  • 19. Questions • Level order traversal of a rooted tree can be done by starting from the root and performing • preorder traversal • in-order traversal • depth first search • breadth first search
  • 20. Binary Trees • General tree: a tree each of whose nodes may have any number of children • n-ary tree: a tree each of whose nodes may have no more than n children • Binary tree: a tree each of whose nodes may have no more than 2 children • i.e. a binary tree is a tree with degree (arity) 2 • The children (if present) are called the left child and right child
  • 21. • Recursive definition of a binary tree: it is • The empty tree • Or, a tree which has a root whose left and right subtrees are binary trees • A binary tree is a positional tree, i.e. it matters whether the subtree is left or right Binary Trees
  • 23. Tree Traversals • A traversal of a tree requires that each node of the tree be visited once • Example: a typical reason to traverse a tree is to display the data stored at each node of the tree • Standard traversal orderings: • preorder • inorder • postorder • level-order
  • 24. Traversals We’ll trace the different traversals using this tree; recursive calls, returns, and “visits” will be numbered in the order they occur A I H D E B F C G
  • 25. Preorder Traversal • Start at the root • Visit each node, followed by its children; we will choose to visit left child before right • Recursive algorithm for preorder traversal: • If tree is not empty, • Visit root node of tree • Perform preorder traversal of its left subtree • Perform preorder traversal of its right subtree
  • 26. Preorder Traversal 1: visit A 29: visit I 9: visit H 5: visit D 17: visit E 3: visit B 27: visit F 25: visit C 39: visit G Nodes are visited in the order ABDHECFIG . . . . . . . . . 6 4 2 11 10 8 7 16 15 14 13 12 21 20 19 18 28 26 24 23 22 34 33 32 31 30 38 37 45 44 43 42 41 40 35 36
  • 27.
  • 28.
  • 29.
  • 30.
  • 31. Inorder Traversal • Start at the root • Visit the left child of each node, then the node, then any remaining nodes • Recursive algorithm for inorder traversal • If tree is not empty, • Perform inorder traversal of left subtree of root • Visit root node of tree • Perform inorder traversal of its right subtree
  • 32.
  • 33. Inorder Traversal 23: visit A 29: visit I 9: visit H 5: visit D 18: visit E 14: visit B 33: visit F 37: visit C 41: visit G Nodes are visited in the order DHBEAIFCG . . . . . . . . . 3 2 1 8 7 6 4 15 13 12 11 10 20 19 17 16 26 25 24 22 21 32 31 30 28 27 38 36 45 44 43 42 40 39 34 35
  • 34. Postorder Traversal • Start at the root • Visit the children of each node, then the node • Recursive algorithm for postorder traversal • If tree is not empty, • Perform postorder traversal of left subtree of root • Perform postorder traversal of right subtree of root • Visit root node of tree
  • 35. Postorder Traversal 45: visit A 30: visit I 10: visit H 12: visit D 19: visit E 21: visit B 34: visit F 43: visit C 41: visit G Nodes are visited in the order HDEBIFGCA . . . . . . . . . 3 2 1 7 6 5 4 14 13 11 9 8 18 17 16 15 25 24 23 22 20 31 29 28 27 26 36 35 44 42 40 39 38 37 32 33
  • 36. Things to Note • Note that the relative order of the recursive calls in preorder, inorder and post order traversals is the same • The only differences stem from where the visiting of the root node of a subtree actually takes place
  • 37. Level Order Traversal • Start at the root • Visit the nodes at each level, from left to right • Is there a recursive algorithm for a level order traversal?
  • 38. Level Order Traversal A I H D E B F C G Nodes will be visited in the order ABCDEFGHI
  • 39. Iterative Binary Tree Traversals • In recursive tree traversals, the Java call stack keeps track of where we are in the tree (by means of the call frames for each call) • In iterative traversals, the programmer needs to keep track! • An iterative traversal uses a container to store references to nodes not yet visited • Order of visiting will depend on the type of container being used (stack, queue, etc.)
  • 40. 10-40 An Iterative Traversal Algorithm // Assumption: the tree is not empty Create an empty container to hold references to nodes yet to be visited. Put reference to the root node in the container. While the container is not empty { Remove a reference x from the container. Visit the node x points to. Put references to non-empty children of x in the container. } }
  • 41. 10-41 • Container is a stack: if we push the right successor of a node before the left successor, we get preorder traversal • Container is a queue: if we enqueue the left successor before the right, we get a level order traversal • Exercise: Trace the iterative tree traversal algorithm using as containers • a stack • a queue Iterative Binary Tree Traversals
  • 42. 10-42 Traversal Analysis • Consider a binary tree with n nodes • How many recursive calls are there at most? • For each node, 2 recursive calls at most • So, 2*n recursive calls at most • So, a traversal is O(n)
  • 43. 10-43 Operations on a Binary Tree • What might we want to do with a binary tree? • Add an element (but where?) • Remove an element (but from where?) • Is the tree empty? • Get size of the tree (i.e. how many elements) • Traverse the tree (in preorder, inorder, postorder, level order)
  • 44. 10-44 Discussion • It is difficult to have a general add operation, until we know the purpose of the tree (we will discuss binary search trees later) • We could add “randomly”: go either right or left, and add at the first available spot
  • 45. 10-45 Discussion • Similarly, where would a general remove operation remove from? • We could arbitrarily choose to remove, say, the leftmost leaf • If random choice, what would happen to the children and descendants of the element that was removed? What does the parent of the removed element now point to? • What if the removed element is the root?
  • 46. 10-46 Possible Binary Tree Operations Operation Description removeLeftSubtree Removes the left subtree of the root removeRightSubtree Removes the right subtree of the root removeAllElements Removes all elements from the tree isEmpty Determines whether the tree is empty size Determines the number of elements in the tree contains Determines if a particular element is in the tree find Returns a reference to the specified target, if found toString Returns a string representation of tree’s contents iteratorInOrder Returns an iterator for an inorder traversal iteratorPreOrder Returns an iterator for a preorder traversal iteratorPostOrder Returns an iterator for a postorder traversal iteratorLevelOrder Returns an iterator for a levelorder traversal
  • 47. 10-47 Binary Tree Operations • Our textbook has a smaller set of operations for the BinaryTreeADT • See BinaryTreeADT.java
  • 48. 10-48 Linked Binary Tree Implementation • To represent the binary tree, we will use a linked structure of nodes • root: reference to the node that is the root of the tree • count: keeps track of the number of nodes in the tree • First, how will we represent a node of a binary tree?
  • 49. 10-49 Binary Tree Node • A binary tree node will contain • a reference to a data element • references to its left and right children left and right children are binary tree nodes themselves
  • 50. 10-50 BinaryTreeNode class • Represents a node in a binary tree • Attributes: • element: reference to data element • left: reference to left child of the node • right: reference to right child of the node • See BinaryTreeNode.java • Note that the attributes here are protected • This means that they can be accessed directly from any class that is in the same package as BinaryTreeNode.java
  • 51. 10-51 A BinaryTreeNode Object protected T element; protected BinaryTreeNode<T> left, right; element data object left right Note that either or both of the left and right references could be null
  • 52. 10-52 LinkedBinaryTree Class • Attributes: protected BinaryTreeNode<T> root; protected int count; • The attributes are protected so that they can be accessed directly in any subclass of the LinkedBinaryTree class • We will be looking at a very useful kind of binary tree called a Binary Search Tree later
  • 53. 10-53 LinkedBinaryTree Class • Constructors: //Creates empty binary tree public LinkedBinaryTree() { count = 0; root = null; } //Creates binary tree with specified element as its root public LinkedBinaryTree (T element) { count = 1; root = new BinaryTreeNode<T> (element); }
  • 54. 10-54 /* Returns a reference to the specified target element if it is found in this binary tree. Throws an ElementNotFoundException if not found. */ public T find(T targetElement) throws ElementNotFoundException { BinaryTreeNode<T> current = findAgain( targetElement, root ); if ( current == null ) throw new ElementNotFoundException("binary tree"); return (current.element); } find method
  • 55. 10-55 Discussion • What is element in this statement from the method? return (current.element); • If element were private rather than protected in BinaryTreeNode.java, what would be need in order to access it? • We will now look at the helper method findAgain …
  • 56. 10-56 private BinaryTreeNode<T> findAgain(T targetElement, BinaryTreeNode<T> next) { if (next == null) return null; if (next.element.equals(targetElement)) return next; BinaryTreeNode<T> temp = findAgain(targetElement, next.left); if (temp == null) temp = findAgain(targetElement, next.right); return temp; } findAgain helper method
  • 57. 10-57 Discussion • What kind of method is findAgain? • What is the base case? • There are two! • What is the recursive part?
  • 58. 10-58 /* Performs an inorder traversal on this binary tree by calling a recursive inorder method that starts with the root. Returns an inorder iterator over this binary tree */ public Iterator<T> iteratorInOrder() { ArrayUnorderedList<T> tempList = new ArrayUnorderedList<T>(); inorder (root, tempList); return tempList.iterator(); } iteratorInOrder method
  • 59. 10-59 Discussion • iteratorInOrder is returning an iterator object • It will perform the iteration in inorder • But where is that iterator coming from? return tempList.iterator(); • Let’s now look at the helper method inorder …
  • 60. 10-60 /* Performs a recursive inorder traversal. Parameters are: the node to be used as the root for this traversal, the temporary list for use in this traversal */ protected void inorder (BinaryTreeNode<T> node, ArrayUnorderedList<T> tempList) { if (node != null) { inorder (node.left, tempList); tempList.addToRear(node.element); inorder (node.right, tempList); } } inorder helper method
  • 61. 10-61 Discussion • Recall the recursive algorithm for inorder traversal: • If tree is not empty, • Perform inorder traversal of left subtree of root • Visit root node of tree • Perform inorder traversal of its right subtree • That’s exactly the order that is being implemented here! • What is “visiting” the root node here?
  • 62. 10-62 Discussion • The data elements of the tree (i.e. items of type T) are being temporarily added to an unordered list, in inorder order • Why use an unordered list?? • Why not? We already have this collection, with its iterator operation that we can use!
  • 63. 10-63 Using Binary Trees: Expression Trees • Programs that manipulate or evaluate arithmetic expressions can use binary trees to hold the expressions • An expression tree represents an arithmetic expression such as (5 – 3) * 4 + 9 / 2 • Root node and interior nodes contain operations • Leaf nodes contain operands
  • 64. 10-64 Example: An Expression Tree / - 3 5 + (5 – 3) * 4 + 9 / 2 4 * 9 2
  • 65. 10-65 Evaluating Expression Trees • We can use an expression tree to evaluate an expression • We start the evaluation at the bottom left • What kind of traversal is this?
  • 66. 10-66 Evaluating an Expression Tree - 5 7 8 / 2 9 * This tree represents the expression (9 / 2 + 7) * (8 – 5) Evaluation is based on postorder traversal: If root node is a leaf, return the associated value. Recursively evaluate expression in left subtree. Recursively evaluate expression in right subtree. Perform operation in root node on these two values, and return result. +
  • 67. 10-67 Building an Expression Tree • Now we know how to evaluate an expression represented by an expression tree • But, how do we build an expression tree? • We will build it from the postfix form of the expression • Exercise: develop the algorithm by following the diagrams on the next pages
  • 68. 10-68 Building an Expression Tree • The algorithm will use a stack of ExpressionTree objects • An ExpressionTree is a special case of a binary tree • The ExpressionTree constructor has 3 parameters: • Reference to data item • Reference to left child • Reference to right child • That's all you need to know to develop the algorithm!
  • 69. 10-69 Build an expression tree from the postfix expression 5 3 - 4 * 9 + Token 5 push(new ExpressionTree(5,null,null)); Processing Step(s) Expression Tree Stack (top at right) 5 Token 3 push(new ExpressionTree(3,null,null)); Processing Step(s) Expression Tree Stack (top at right) 5 3
  • 70. 10-70 Token - op2 = pop op1 = pop push(new ExpressionTree(-,op1,op2)); Processing Step(s) Expression Tree Stack (top at right) 5 - 3
  • 72. 10-72 Token * op2 = pop op1 = pop push(new ExpressionTree(*,op1,op2)); Processing Step(s) Expression Tree Stack (top at right) 5 - 3 4 *
  • 74. 10-74 Token + op2 = pop op1 = pop push(new ExpressionTree(+,op1,op2)); Processing Step(s) Expression Tree Stack (top at right) 5 - 3 4 * 9 + End of the expression has been reached, and the full expression tree is the only tree left on the stack