The Tree ADT
10-2
Objectives
• Define trees as data structures
• Discuss tree traversal algorithms
• Discuss a binary tree implementation
10-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
10-4
Example: Computer File System
Root directory of C drive
Documents and Settings Program Files My Music
Desktop Favorites Start Menu Microsoft Office
Adobe
10-5
Example: Table of Contents
Java Software Structures
Introduction Analysis of Algorithms Index
Software
Quality
Data
Structures
Algorithm
Efficiency
Time Complexity
Big Oh
Notatio
3-6
Example: Java’s Class Hierarchy
Error
Object
Exception Square
String
Rectangle
Throwable
Array
. . .
.
.
.
.
.
.
10-7
Tree Definition
• A tree is 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)
• What kind of definition is this?
• What is the base case?
• What is the recursive part?
10-8
Tree Definition
Subtrees of
the root
Root
10-9
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
10-10
Tree Terminology
node or
vertex
Root
edge
arc, or
link
10-11
• 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-12
Tree Terminology
A
B C E
D
F G
H
Node A is the parent of nodes
B, C, D, E
Node E is a child
of node A
Nodes B, C, D, E
are siblings
Nodes F, B, and A are ancestors of node H
Nodes F, G
and H are
descendants
of node B
All nodes, except A, are descendants of node A
10-13
Tree Terminology
• Leaf node: a node without children
• Internal node: a node with one of more
children
10-14
Tree Terminology
Leaf
nodes or
external
nodes
Root
Interior or
internal
nodes
10-15
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?
10-16
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?
10-17
Tree Terminology
Root
A
B
F H
E
J
C D
I
L M N
G
K
Height = 3
A path
Path of
length 3
10-18
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 height of a tree
in terms of levels?
10-19
Level of a Node
Level 0
Level 1
Level 2
Level 3
10-20
Subtrees
• A 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
10-21
Subtrees
Subtrees of the
node labeled E
E
10-22
More Tree Terminology
• Degree of a node: the number of
children it has
• Degree of a tree: the maximum of the
degrees of the nodes of the tree
10-23
Degree
A
B
F H
E
J
C D
I
L M
G
K
4
2 0 0 3
1
0
0 1 0 1
0 0
Degrees of the nodes are indicated beside the nodes
10-24
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 2
• The children of a node (if present) are
called the left child and right child
10-25
• 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 an ordered tree, i.e. it
matters whether a child is a left or right
child
Binary Trees
10-26
Binary Tree
A
I
H
D E
B
F
C
G
Left child of A Right child of A
10-27
Tree Traversals
• A traversal of a tree starts at the root
and visits each node of the tree once.
• Common tree traversals:
• preorder
• inorder
• postorder
• level-order
10-28
Preorder Traversal
• Start at the root
• Visit each node, followed by its children; we will
visit the left child before the right one
• 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
• What is the base case?
• What is the recursive part?
10-29
Preorder Traversal
public void preorder (BinaryTreeNode<T> r) {
if (r != null) {
visit(r);
preorder (r.getLeftChild());
preorder (r.getRightChild());
}
}
10-30
A
I
H
D E
B
F
C
G
Preorder Traversal
In a preorder traversal of this tree the nodes are visited in the order
ABDHECFIG
10-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
10-32
Inorder Traversal
public void inorder (BinaryTreeNode<T> r) {
if (r != null) {
inorder (r.getLeftChild());
visit(r);
inorder (r.getRightChild());
}
}
10-33
A
I
H
D E
B
F
C
G
In an inorder traversal of this tree the nodes are visited in the order
DHBEAIFCG
Inorder Traversal
10-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
10-35
Postorder Traversal
public void postorder (BinaryTreeNode<T> r) {
if (r != null) {
postorder (r.getLeftChild());
postorder (r.getRightChild());
visit(r);
}
}
10-36
A
I
H
D E
B
F
C
G
In an postorder traversal of this tree the nodes are visited in the
order HDEBIFGCA
Postorder Traversal
10-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?
10-38
Level Order Traversal
A
I
H
D E
B
F
C
G
In a level order traversal of this tree the nodes will be visited in the
order ABCDEFGHI
10-39
Level Order Traversal
We need to use a queue:
• Start at the root
• Visit the nodes at each level, from left to right
A
I
H
D E
B
F
C
G
queue
10-40
Level Order Traversal
• Put A in the queue
A
I
H
D E
B
F
C
G
A
10-41
Level Order Traversal
1. Remove the first node from the queue
A
I
H
D E
B
F
C
G
A
10-42
Level Order Traversal
2. Enqueue all neighbours of the node that was
removed from the queue
A
I
H
D E
B
F
C
G
A
B C
10-43
Level Order Traversal
Repeat steps 1 and 2 until the queue is empty
A
I
H
D E
B
F
C
G
A B
C
10-44
Level Order Traversal
A
I
H
D E
B
F
C
G
A B
C D E
Repeat steps 1 and 2 until the queue is empty
10-45
Level Order Traversal
A
I
H
D E
B
F
C
G
A B C
D E F G
Repeat steps 1 and 2 until the queue is empty
10-46
Level Order Traversal
A
I
H
D E
B
F
C
G
A B C D
E F G H
Repeat steps 1 and 2 until the queue is empty
10-47
Level Order Traversal
A
I
H
D E
B
F
C
G
A B C D E
F G H
Repeat steps 1 and 2 until the queue is empty
10-48
Level Order Traversal
A
I
H
D E
B
F
C
G
A B C D E F
G H I
Repeat steps 1 and 2 until the queue is empty
10-49
Level Order Traversal
A
I
H
D E
B
F
C
G
A B C D E F G
H I
Repeat steps 1 and 2 until the queue is empty
10-50
Level Order Traversal
A
I
H
D E
B
F
C
G
A B C D E F G H
I
Repeat steps 1 and 2 until the queue is empty
10-51
Level Order Traversal
A
I
H
D E
B
F
C
G
Level order traversal: A B C D E F G H I
The queue is empty. The algorithm terminates
10-52
Level order Traversal
Algorithm levelOrder (root) {
Input: root of a binary tree
Output: Nothing, but visit the nodes of the tree in level order
if root = null then return
Q = empty queue
Q.enqueue(root);
while Q is not empty do {
v = Q.dequeue();
visit(v);
if v.leftChild() != null then Q.enqueue(v.leftChild());
if v.rightChild() != null then Q.enqueue(v.rightChild());
}
}
10-53
Iterative Binary Tree Traversals
• In recursive tree traversals, the Java execution
stack keeps track of where we are in the tree
(by means of the activation records 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
• The order in which the nodes are visited will depend
on the type of container being used (stack, queue,
etc.)
10-54
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-55
• Container is a stack: if we push the right child of
a node before the left child, we get preorder
traversal
• Container is a queue: if we enqueue the left
child before the right, we get a level order
traversal
Iterative Binary Tree Traversals
10-56
Operations on a Binary Tree
• What might we want to do with a binary
tree?
• Add an element
• Remove an element
• Is the tree empty?
• Get size of the tree (i.e. how many
elements)
• Traverse the tree (in preorder, inorder,
postorder, level order)
10-57
Possible Binary Tree Operations
Operation Description
getRoot Returns a reference to the root of the tree
isEmpty Determines whether the tree is empty
size Determines the number of elements 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
9-58
2-58
What is an Iterator?
An iterator is an abstract data type that allows us
to iterate through the elements of a collection one
by one
Operations
• next: next element of the collection; ERROR if
the element does not exist
• hasNext: true if there are more elements in the
collection; false otherwise
• remove: removes the last element returned by
the iterator
9-59
2-59
Iterator Interface
public interface Iterator<T> {
public boolean hasNext( );
public T next( );
public void remove( ); // (optional operation)
}
This interface is in the java.util package of Java
Binary Tree ADT
package binaryTree;
import java.util.Iterator;
public interface BinaryTreeADT<T> {
public T getRoot ();
public boolean isEmpty();
public int size();
public T find (T targetElement) throws
ElementNotFoundException;
public String toString();
public Iterator<T> iteratorInOrder();
public Iterator<T> iteratorPreOrder();
public Iterator<T> iteratorPostOrder();
public Iterator<T> iteratorLevelOrder();
}
10-60
10-61
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-62
Linked Binary Tree Implementation
• A binary tree node will contain
• a reference to a data element
• references to its left and right children and
to its parent
left and right children are binary tree nodes themselves
10-63
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
• parent: reference to the parent of the node
10-64
A BinaryTreeNode Object
protected T element;
protected BinaryTreeNode<T> left, right, parent;
Note that either or both of the left and right references could be null
What is the meaning of protected?
10-65
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
10-66
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-67
/* 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);
}
10-68
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-69
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;
}
10-70
Discussion
• What kind of method is findAgain?
• What is the base case?
• There are two!
• What is the recursive part?
10-71
/* 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();
}
10-72
Discussion
• iteratorInOrder returns 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-73
/* 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);
}
}
10-74
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 is exactly the order that is being
implemented here!
• What is “visiting” the root node here?
10-75
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-76
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-77
Example: An Expression Tree
/
-
3
5
+
(5 – 3) * 4 + 9 / 2
4
*
9 2
10-78
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-79
Evaluating an Expression Tree
-
5
7 8
/
2
9
* This tree represents
the expression
(9 / 2 + 7) * (8 – 5)
Evaluation is based on a 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-80
Evaluating an Expression Tree
-
5
7 8
/
2
9
*
+
10-81
Evaluating an Expression Tree
-
5
7 8
/
2
9
*
+
9/2 = 4.5
10-82
Evaluating an Expression Tree
-
5
7 8
/
2
9
*
+
4.5
4.5 + 7 = 11.5
10-83
Evaluating an Expression Tree
-
5
7 8
/
2
9
*
+
4.5
11.5 8 – 5 = 3
10-84
Evaluating an Expression Tree
-
5
7 8
/
2
9
*
+
4.5
11.5 3
11.5 * 3 = 34.5
10-85
Optional Notes: 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-86
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-87
Build an expression tree from the postfix
expression 5 3 - 4 * 9 +
Symbol
5 push(new ExpressionTree(5,null,null));
Processing Step(s)
Expression Tree Stack (top at right)
5
Symbol
3
push(new ExpressionTree(3,null,null));
Processing Step(s)
Expression Tree Stack (top at right)
5 3
10-88
Symbol
-
op2 = pop
op1 = pop
push(new ExpressionTree(-,op1,op2));
Processing Step(s)
Expression Tree Stack (top at right)
5
-
3
10-89
Symbol
4
push(new ExpressionTree(4,null,null));
Processing Step(s)
Expression Tree Stack (top at right)
5
-
3
4
10-90
Symbol
*
op2 = pop
op1 = pop
push(new ExpressionTree(*,op1,op2));
Processing Step(s)
Expression Tree Stack (top at right)
5
-
3
4
*
10-91
Symbol
9
push(new ExpressionTree(9,null,null));
Processing Step(s)
Expression Tree Stack (top at right)
5
-
3
4
* 9
10-92
Symbol
+
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

More Related Content

PPTX
PPTX
tree Data Structures in python Traversals.pptx
PPTX
unit 4 for trees data structure notes it is
PPT
Tree 11.ppt
PPT
Binary tree traversal ppt - 02.03.2020
PPTX
Data Structures and Algorithms - Lecture 10 - Thushapan.pptx
tree Data Structures in python Traversals.pptx
unit 4 for trees data structure notes it is
Tree 11.ppt
Binary tree traversal ppt - 02.03.2020
Data Structures and Algorithms - Lecture 10 - Thushapan.pptx

Similar to CS1027-Trees-2020 lecture one .pdf (20)

PPT
Tree and Binary Search tree
PPT
Ch12 Tree
PPTX
Unit-VStackStackStackStackStackStack.pptx
PPT
PPTX
Lecture 8 data structures and algorithms
PPTX
Tree Data Structure Tree Data Structure Details
PPTX
binary tree.pptx
PPT
Lecture 5 trees
PPTX
trees in data structure
PPT
Binary trees
PPTX
07-Lecture.pptxlkjslkjdfkjskljdflksj;fdkj
PPTX
Lecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptx
PPT
9. TREE Data Structure Non Linear Data Structure
PPT
Data Structure and Algorithms Binary Tree
PPT
tutorial-tree (3).ppt
PPT
ds 10-Binary Tree.ppt
PPT
binary tree power point presentation for iT
PPT
Data structures algoritghm for binary tree method.ppt
PPTX
Tree.pptx
Tree and Binary Search tree
Ch12 Tree
Unit-VStackStackStackStackStackStack.pptx
Lecture 8 data structures and algorithms
Tree Data Structure Tree Data Structure Details
binary tree.pptx
Lecture 5 trees
trees in data structure
Binary trees
07-Lecture.pptxlkjslkjdfkjskljdflksj;fdkj
Lecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptx
9. TREE Data Structure Non Linear Data Structure
Data Structure and Algorithms Binary Tree
tutorial-tree (3).ppt
ds 10-Binary Tree.ppt
binary tree power point presentation for iT
Data structures algoritghm for binary tree method.ppt
Tree.pptx
Ad

More from AliaaTarek5 (11)

PPTX
RUDC project.pptxl;ml;ml';m;m';m';m;'';m';m';m';
PPTX
Human-Machine-Interface-HMI-Bridging-Humans-and-Technology.pptx
PDF
lecture_14_state_space_canonical_forms.pdf
PPT
Design via root locus lead lag compensation
PDF
Section 5 Root Locus Analysis lecture 55
PPTX
Introduction-to-Mechanical-Accelerometers.pptx
PPT
تطبيقات التكاليف ودراسات الجدوى (2).ppt
PPTX
Chapter-3.pptx
PPTX
Chapter 2.pptx
PPTX
Chapter 1 digital design.pptx
PDF
Git_tutorial.pdf
RUDC project.pptxl;ml;ml';m;m';m';m;'';m';m';m';
Human-Machine-Interface-HMI-Bridging-Humans-and-Technology.pptx
lecture_14_state_space_canonical_forms.pdf
Design via root locus lead lag compensation
Section 5 Root Locus Analysis lecture 55
Introduction-to-Mechanical-Accelerometers.pptx
تطبيقات التكاليف ودراسات الجدوى (2).ppt
Chapter-3.pptx
Chapter 2.pptx
Chapter 1 digital design.pptx
Git_tutorial.pdf
Ad

Recently uploaded (20)

PDF
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
PDF
Visual Aids for Exploratory Data Analysis.pdf
PDF
737-MAX_SRG.pdf student reference guides
PPTX
Module 8- Technological and Communication Skills.pptx
PDF
Exploratory_Data_Analysis_Fundamentals.pdf
PDF
August 2025 - Top 10 Read Articles in Network Security & Its Applications
PPT
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
PPTX
Fundamentals of safety and accident prevention -final (1).pptx
PPTX
ASME PCC-02 TRAINING -DESKTOP-NLE5HNP.pptx
PPTX
"Array and Linked List in Data Structures with Types, Operations, Implementat...
PPTX
Feature types and data preprocessing steps
PDF
Soil Improvement Techniques Note - Rabbi
PPTX
tack Data Structure with Array and Linked List Implementation, Push and Pop O...
PDF
UNIT no 1 INTRODUCTION TO DBMS NOTES.pdf
PDF
ChapteR012372321DFGDSFGDFGDFSGDFGDFGDFGSDFGDFGFD
PPTX
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
PDF
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
PPTX
Management Information system : MIS-e-Business Systems.pptx
PDF
Design Guidelines and solutions for Plastics parts
PPTX
Amdahl’s law is explained in the above power point presentations
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
Visual Aids for Exploratory Data Analysis.pdf
737-MAX_SRG.pdf student reference guides
Module 8- Technological and Communication Skills.pptx
Exploratory_Data_Analysis_Fundamentals.pdf
August 2025 - Top 10 Read Articles in Network Security & Its Applications
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
Fundamentals of safety and accident prevention -final (1).pptx
ASME PCC-02 TRAINING -DESKTOP-NLE5HNP.pptx
"Array and Linked List in Data Structures with Types, Operations, Implementat...
Feature types and data preprocessing steps
Soil Improvement Techniques Note - Rabbi
tack Data Structure with Array and Linked List Implementation, Push and Pop O...
UNIT no 1 INTRODUCTION TO DBMS NOTES.pdf
ChapteR012372321DFGDSFGDFGDFSGDFGDFGDFGSDFGDFGFD
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
Management Information system : MIS-e-Business Systems.pptx
Design Guidelines and solutions for Plastics parts
Amdahl’s law is explained in the above power point presentations

CS1027-Trees-2020 lecture one .pdf

  • 2. 10-2 Objectives • Define trees as data structures • Discuss tree traversal algorithms • Discuss a binary tree implementation
  • 3. 10-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. 10-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. 10-5 Example: Table of Contents Java Software Structures Introduction Analysis of Algorithms Index Software Quality Data Structures Algorithm Efficiency Time Complexity Big Oh Notatio
  • 6. 3-6 Example: Java’s Class Hierarchy Error Object Exception Square String Rectangle Throwable Array . . . . . . . . .
  • 7. 10-7 Tree Definition • A tree is 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) • What kind of definition is this? • What is the base case? • What is the recursive part?
  • 9. 10-9 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
  • 11. 10-11 • 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
  • 12. 10-12 Tree Terminology A B C E D F G H Node A is the parent of nodes B, C, D, E Node E is a child of node A Nodes B, C, D, E are siblings Nodes F, B, and A are ancestors of node H Nodes F, G and H are descendants of node B All nodes, except A, are descendants of node A
  • 13. 10-13 Tree Terminology • Leaf node: a node without children • Internal node: a node with one of more children
  • 15. 10-15 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?
  • 16. 10-16 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?
  • 17. 10-17 Tree Terminology Root A B F H E J C D I L M N G K Height = 3 A path Path of length 3
  • 18. 10-18 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 height of a tree in terms of levels?
  • 19. 10-19 Level of a Node Level 0 Level 1 Level 2 Level 3
  • 20. 10-20 Subtrees • A 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
  • 22. 10-22 More Tree Terminology • Degree of a node: the number of children it has • Degree of a tree: the maximum of the degrees of the nodes of the tree
  • 23. 10-23 Degree A B F H E J C D I L M G K 4 2 0 0 3 1 0 0 1 0 1 0 0 Degrees of the nodes are indicated beside the nodes
  • 24. 10-24 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 2 • The children of a node (if present) are called the left child and right child
  • 25. 10-25 • 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 an ordered tree, i.e. it matters whether a child is a left or right child Binary Trees
  • 26. 10-26 Binary Tree A I H D E B F C G Left child of A Right child of A
  • 27. 10-27 Tree Traversals • A traversal of a tree starts at the root and visits each node of the tree once. • Common tree traversals: • preorder • inorder • postorder • level-order
  • 28. 10-28 Preorder Traversal • Start at the root • Visit each node, followed by its children; we will visit the left child before the right one • 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 • What is the base case? • What is the recursive part?
  • 29. 10-29 Preorder Traversal public void preorder (BinaryTreeNode<T> r) { if (r != null) { visit(r); preorder (r.getLeftChild()); preorder (r.getRightChild()); } }
  • 30. 10-30 A I H D E B F C G Preorder Traversal In a preorder traversal of this tree the nodes are visited in the order ABDHECFIG
  • 31. 10-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. 10-32 Inorder Traversal public void inorder (BinaryTreeNode<T> r) { if (r != null) { inorder (r.getLeftChild()); visit(r); inorder (r.getRightChild()); } }
  • 33. 10-33 A I H D E B F C G In an inorder traversal of this tree the nodes are visited in the order DHBEAIFCG Inorder Traversal
  • 34. 10-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. 10-35 Postorder Traversal public void postorder (BinaryTreeNode<T> r) { if (r != null) { postorder (r.getLeftChild()); postorder (r.getRightChild()); visit(r); } }
  • 36. 10-36 A I H D E B F C G In an postorder traversal of this tree the nodes are visited in the order HDEBIFGCA Postorder Traversal
  • 37. 10-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. 10-38 Level Order Traversal A I H D E B F C G In a level order traversal of this tree the nodes will be visited in the order ABCDEFGHI
  • 39. 10-39 Level Order Traversal We need to use a queue: • Start at the root • Visit the nodes at each level, from left to right A I H D E B F C G queue
  • 40. 10-40 Level Order Traversal • Put A in the queue A I H D E B F C G A
  • 41. 10-41 Level Order Traversal 1. Remove the first node from the queue A I H D E B F C G A
  • 42. 10-42 Level Order Traversal 2. Enqueue all neighbours of the node that was removed from the queue A I H D E B F C G A B C
  • 43. 10-43 Level Order Traversal Repeat steps 1 and 2 until the queue is empty A I H D E B F C G A B C
  • 44. 10-44 Level Order Traversal A I H D E B F C G A B C D E Repeat steps 1 and 2 until the queue is empty
  • 45. 10-45 Level Order Traversal A I H D E B F C G A B C D E F G Repeat steps 1 and 2 until the queue is empty
  • 46. 10-46 Level Order Traversal A I H D E B F C G A B C D E F G H Repeat steps 1 and 2 until the queue is empty
  • 47. 10-47 Level Order Traversal A I H D E B F C G A B C D E F G H Repeat steps 1 and 2 until the queue is empty
  • 48. 10-48 Level Order Traversal A I H D E B F C G A B C D E F G H I Repeat steps 1 and 2 until the queue is empty
  • 49. 10-49 Level Order Traversal A I H D E B F C G A B C D E F G H I Repeat steps 1 and 2 until the queue is empty
  • 50. 10-50 Level Order Traversal A I H D E B F C G A B C D E F G H I Repeat steps 1 and 2 until the queue is empty
  • 51. 10-51 Level Order Traversal A I H D E B F C G Level order traversal: A B C D E F G H I The queue is empty. The algorithm terminates
  • 52. 10-52 Level order Traversal Algorithm levelOrder (root) { Input: root of a binary tree Output: Nothing, but visit the nodes of the tree in level order if root = null then return Q = empty queue Q.enqueue(root); while Q is not empty do { v = Q.dequeue(); visit(v); if v.leftChild() != null then Q.enqueue(v.leftChild()); if v.rightChild() != null then Q.enqueue(v.rightChild()); } }
  • 53. 10-53 Iterative Binary Tree Traversals • In recursive tree traversals, the Java execution stack keeps track of where we are in the tree (by means of the activation records 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 • The order in which the nodes are visited will depend on the type of container being used (stack, queue, etc.)
  • 54. 10-54 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. }
  • 55. 10-55 • Container is a stack: if we push the right child of a node before the left child, we get preorder traversal • Container is a queue: if we enqueue the left child before the right, we get a level order traversal Iterative Binary Tree Traversals
  • 56. 10-56 Operations on a Binary Tree • What might we want to do with a binary tree? • Add an element • Remove an element • Is the tree empty? • Get size of the tree (i.e. how many elements) • Traverse the tree (in preorder, inorder, postorder, level order)
  • 57. 10-57 Possible Binary Tree Operations Operation Description getRoot Returns a reference to the root of the tree isEmpty Determines whether the tree is empty size Determines the number of elements 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
  • 58. 9-58 2-58 What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one Operations • next: next element of the collection; ERROR if the element does not exist • hasNext: true if there are more elements in the collection; false otherwise • remove: removes the last element returned by the iterator
  • 59. 9-59 2-59 Iterator Interface public interface Iterator<T> { public boolean hasNext( ); public T next( ); public void remove( ); // (optional operation) } This interface is in the java.util package of Java
  • 60. Binary Tree ADT package binaryTree; import java.util.Iterator; public interface BinaryTreeADT<T> { public T getRoot (); public boolean isEmpty(); public int size(); public T find (T targetElement) throws ElementNotFoundException; public String toString(); public Iterator<T> iteratorInOrder(); public Iterator<T> iteratorPreOrder(); public Iterator<T> iteratorPostOrder(); public Iterator<T> iteratorLevelOrder(); } 10-60
  • 61. 10-61 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?
  • 62. 10-62 Linked Binary Tree Implementation • A binary tree node will contain • a reference to a data element • references to its left and right children and to its parent left and right children are binary tree nodes themselves
  • 63. 10-63 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 • parent: reference to the parent of the node
  • 64. 10-64 A BinaryTreeNode Object protected T element; protected BinaryTreeNode<T> left, right, parent; Note that either or both of the left and right references could be null What is the meaning of protected?
  • 65. 10-65 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
  • 66. 10-66 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); }
  • 67. 10-67 /* 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); }
  • 68. 10-68 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 …
  • 69. 10-69 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; }
  • 70. 10-70 Discussion • What kind of method is findAgain? • What is the base case? • There are two! • What is the recursive part?
  • 71. 10-71 /* 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(); }
  • 72. 10-72 Discussion • iteratorInOrder returns 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 …
  • 73. 10-73 /* 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); } }
  • 74. 10-74 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 is exactly the order that is being implemented here! • What is “visiting” the root node here?
  • 75. 10-75 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!
  • 76. 10-76 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
  • 77. 10-77 Example: An Expression Tree / - 3 5 + (5 – 3) * 4 + 9 / 2 4 * 9 2
  • 78. 10-78 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?
  • 79. 10-79 Evaluating an Expression Tree - 5 7 8 / 2 9 * This tree represents the expression (9 / 2 + 7) * (8 – 5) Evaluation is based on a 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. +
  • 80. 10-80 Evaluating an Expression Tree - 5 7 8 / 2 9 * +
  • 81. 10-81 Evaluating an Expression Tree - 5 7 8 / 2 9 * + 9/2 = 4.5
  • 82. 10-82 Evaluating an Expression Tree - 5 7 8 / 2 9 * + 4.5 4.5 + 7 = 11.5
  • 83. 10-83 Evaluating an Expression Tree - 5 7 8 / 2 9 * + 4.5 11.5 8 – 5 = 3
  • 84. 10-84 Evaluating an Expression Tree - 5 7 8 / 2 9 * + 4.5 11.5 3 11.5 * 3 = 34.5
  • 85. 10-85 Optional Notes: 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
  • 86. 10-86 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!
  • 87. 10-87 Build an expression tree from the postfix expression 5 3 - 4 * 9 + Symbol 5 push(new ExpressionTree(5,null,null)); Processing Step(s) Expression Tree Stack (top at right) 5 Symbol 3 push(new ExpressionTree(3,null,null)); Processing Step(s) Expression Tree Stack (top at right) 5 3
  • 88. 10-88 Symbol - op2 = pop op1 = pop push(new ExpressionTree(-,op1,op2)); Processing Step(s) Expression Tree Stack (top at right) 5 - 3
  • 90. 10-90 Symbol * op2 = pop op1 = pop push(new ExpressionTree(*,op1,op2)); Processing Step(s) Expression Tree Stack (top at right) 5 - 3 4 *
  • 92. 10-92 Symbol + 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