lect 8 trees.pptx
TRANSCRIPT
-
8/12/2019 Lect 8 Trees.pptx
1/48
TREES
Lecture 8
-
8/12/2019 Lect 8 Trees.pptx
2/48
2
General Trees
Tree is one of the most important non-linear DataStructures in computing.
Tree structures are important because they allow us toimplement a host of algorithms much faster thanwhen using linear data structures, such as list.
Trees also provide a natural way to organize data inmany areas such as:
File systems
Graphical User Interfaces (GUI)DatabasesWeb Sitesand many other computer systems.
-
8/12/2019 Lect 8 Trees.pptx
3/48
3
Tree Example
ComputersRUs
Sales R&DManufacturing
Laptops DesktopsUS International
Europe Asia Canada
a tree representing the organization of a fictitious corporation
-
8/12/2019 Lect 8 Trees.pptx
4/48
4
Tree Structure
In computer science, a tree is an abstract model of ahierarchical structure, with some objects beingabove and some below others. A tree consists of nodes with a parent-child relationship, rather than the simple before andafter relationship, found between objects insequential ( linear ) structures.A famous example of hierarchical structure ( tree ) is
the family tree .Applications:Organization chartsFile systems
Programming environments
-
8/12/2019 Lect 8 Trees.pptx
5/48
Trees
5
Tree Definitions and Properties
A tree T, is an abstract data type thatstores elements hierarchically.
Except the top element ( root ), eachelement in a tree has a parent and zero
or more children elements. root : node without parent (Node A)
Internal node : node with at least onechild (A, B, C, F)
External node ( leaf ): node withoutchildren (E, I, J, K, G, H, D)
Sibling nodes : Two nodes that arechildren of the same parent are Siblings.
Depth of a node : numberof its ancestorsHeight of a tree :
maximum depth of anynode Ancestors of a node :parent, grandparent,grand- grandparent, etc.Descendants of a node :
child, grandchild, grand-grandchild, etc. Subtree : a tree consistingof a node and itsdescendants
-
8/12/2019 Lect 8 Trees.pptx
6/48
6
Example
A
B DC
G HE F
I J Ksubtree
T root is node A
Internal (branch) nodes arenodes A, B, C, F
External nodes ( leaves ) arenodes E, I, J, K, G, H, D
Depth of node F is 2
Height of T is 3
Ancestors of node H are Cand A
Children of node A are B, Cand D
Nodes B, C and D aresiblings
Descendants of node B areE, F, I, J and K
-
8/12/2019 Lect 8 Trees.pptx
7/48
7
Formal Definition of a Tree
Formally, we define a tree T as a finite set of nodes storingelements such that the nodes have a parent-child relationship,that satisfies the following properties:
If T is nonempty , it has a specially designated node,called the root of T, that has no parent .
Each node v of T other than the root has a unique parent
node w.Every node with parent w is a child of w.
Note that a tree may be empty .
-
8/12/2019 Lect 8 Trees.pptx
8/48
Trees
8
Subtree of Tree T
The subtree of a tree T , rooted at node v is the tree consisting all the descendants of v in T (includingv itself).
Edges and Paths in Trees:An edge of tree T is a pair of nodes (u,v), such that u isthe parent of v, or vice versa.A path of T is a sequence of nodes such that any two
consecutive nodes in the sequence form an edge.As an example of a path, is the sequence A, B, F, K.where (A , B) or (B , A) is an edge .
-
8/12/2019 Lect 8 Trees.pptx
9/48
Trees
9
Ordered Trees
A tree is ordered if there is a linear orderingdefined for the children of each node ;Thats, we can identify the children of a node as
being the first , second , third , and so on.Such an ordering is usually shown by arranging siblings left to right, according to their ordering.
Ordered trees typically indicate the linear order
among siblings by listing them in the correctorder.A famous example of ordered trees is the family tree.
-
8/12/2019 Lect 8 Trees.pptx
10/48
Trees
10
Tree ADT
The tree ADT stores elements at positions , whichare defined relative to neighboring positions .
Positions in a tree are its nodes , and theneighboring positions satisfy the parent-child relationships that define a valid tree .Tree nodes may store arbitrary objects.As with a list position, a position object for a tree supports the method: element() : that returns theobject stored at this position (or node ).The tree ADT supports four types of methods, asfollows.
-
8/12/2019 Lect 8 Trees.pptx
11/48
Trees
11
Methods of a Tree ADT
1. Accessor MethodsWe use positions to abstract nodes . The real power ofnode positions in a tree comes from the accessor
methods of the tree ADT that return and accept positions , such as the following: root(): Return the position of the trees root ; an error
occurs if the tree is empty .
parent(p): Return the position of the parent of p; anerror occurs if p is the root . children(p): Return an iterable collection containing
the children of node p.
-
8/12/2019 Lect 8 Trees.pptx
12/48
Trees12
Notice that :
If a tree T is ordered, then the iterablecollection, children(p), stores the children of
p in their linear order.
If p is an external node, then children(p) isempty.Any method that takes a position as argument
should generate an error condition if that position is invalid.
-
8/12/2019 Lect 8 Trees.pptx
13/48
Trees
13
2. Generic methods
size() : Return the number of nodes in the tree .
isEmpty(): Test whether the tree has any nodes ornot.
Iterator(): Return an iterator of all the elements stored at nodes of the tree .
positions(): Return an iterable collection of all thenodes of the tree .
Methods of a Tree ADT (Cont.)
-
8/12/2019 Lect 8 Trees.pptx
14/48
14
Methods of a Tree ADT (Cont.)
3. Query methodsIn addition to the above fundamental accessor methods, the
tree ADT
also supports the following Boolean query methods:
isInternal(p): Test whether node p is an internal nodeisExternal(p): Test whether node p is an external nodeisRoot(p): Test whether node p is the root node
These methods make programming with tree easier andmore readable, since we can use them in the conditionalsof if -statements and while -loops, rather than using a non-intuitive conditional.
-
8/12/2019 Lect 8 Trees.pptx
15/48
15
Methods of a Tree ADT (Cont.)
4. Update MethodThe tree ADT also supports the following update method:
replace(p, e): Replace with e and return the element stored at node p.
Additional update methods may be defined by datastructures implementing the tree ADT
-
8/12/2019 Lect 8 Trees.pptx
16/48
Trees
16
Tree ADT Exceptions
An interface for the tree ADT uses the followingexceptions to indicate error conditions: InvalidPositionException: This error condition may
be thrown by any method taking a position as anargument to indicate that the position is invalid . BoundaryViolationException : This error condition
may be thrown by method parent() if its called on
the root . EmptyTreeException : This error condition may be
thrown by method root() if its called on an emptytree .
-
8/12/2019 Lect 8 Trees.pptx
17/48
Trees
17
A Linked Structure Implementation of GeneralTrees
A natural way to implement a tree T is to use a linkedstructure , where we represent each node p of T by a position object with the following fields (see Figure):
A reference to the element stored at p.
A link to the parent of p.
A some kind of collection (e.g., a list or array ) to store links tothe children of p .
Also, we store a reference to the root of T and the number ofnodes of T in internal variables .
element
parent
ChildrenCollection
Fig. 7.3 (a) Tree Node
-
8/12/2019 Lect 8 Trees.pptx
18/48
Trees
18
Linked Structure for General Trees
A node is represented by anobject storing
ElementParent nodeSequence of children nodes
Node objects implement thePosition ADT
B
D A
C E
F
B
A D F
C
E
-
8/12/2019 Lect 8 Trees.pptx
19/48
19
Tree Traversal Algorithms
Depth and Height
The depth of a node v in tree T , is the number of ancestors of v, excluding v itself. This definition implies that the
depth of the root of T is 0.Recursive definition of the depth of node v:
If v is the root , then the depth of v is 0. (Base Case)
Otherwise, the depth of v is one plus the depth of the parent of v.
Algorithm depth(T,v)if v is the root of T then
return 0else
return 1 + depth(T,w), where w is the
parent of v in T
-
8/12/2019 Lect 8 Trees.pptx
20/48
Trees
26
Tree Traversal
A traversal of a tree T is a systematic way of accessing , orvisiting all the nodes of T , such that each node is visitedonce.
The specific action associated with the visit of a node v depends on the application of this traversal, for example:
Increment a counter,Update content of v, Perform some computation for v, etc.
There are many types of tree traversals.
-
8/12/2019 Lect 8 Trees.pptx
21/48
Trees
30
Preorder Traversal
Visit each node before recursively visiting its children and descendants ,from left to right (ordered tree) . Root is visited first.
Each node is visited only once.
The preorder traversal is useful to get a linear ordering of nodes of atree.
Application: It is a natural way to print the structure of directories, or print a structured document, e.g. content list.
-
8/12/2019 Lect 8 Trees.pptx
22/48
28
Preorder Traversal
Make Money Fast!
1. Motivations References2. Methods
2.1 StockFraud
2.2 PonziScheme1.1 Greed 1.2 Avidity
2.3 BankRobbery
1
2
3
5
4 6 7 8
9
Algorithm preOrder(T,v)visit(v)for each child w of v in T do
preOrder (T,w) //Recursion
-
8/12/2019 Lect 8 Trees.pptx
23/48
29
Postorder Traversal
The postorder traversal can be viewed as the oppositeof preorder traversal.
It recursively traverses the children of the root first,from left to right , after that, it visits the root nodeitself.
As with preorder , it gives a linear ordering of thenodes of an ordered tree.
Application: compute disk space used by files in adirectory and its subdirectories.
-
8/12/2019 Lect 8 Trees.pptx
24/48
30
Postorder Traversal
In a postorder traversal,a node is visited after itsdescendants.
Algorithm postOrder(T,v)for each child w of v in T do
postOrder(T,w)visit(v)
cs16/
homeworks/ todo.txt1Kprograms/
DDR.java10K
Stocks.java25K
h1c.doc3K
h1nc.doc2K
Robot.java20K
9
3
1
7
2 4 5 6
8
-
8/12/2019 Lect 8 Trees.pptx
25/48
Trees
31
Example
Consider a file system tree T , where external nodesrepresent files and internal nodes represent directories , asshown in last tree figure.Suppose we need to calculate the disk space used by adirectory, which is recursively given by the sum of:
The size of the directory itself The sizes of the files in the directory The space used by the children directories
This Computation can be easily done by postorder traversalof tree T .
-
8/12/2019 Lect 8 Trees.pptx
26/48
32
Other Kinds of Traversals
Inorder Traversal, applied only for Binary trees,where the node is visited in-between its left child andits right child.
Constant-Depth traversal, where we visit all nodesat depth d , from left to right , before we visit thenodes at depth d+1 .
Thus, numbering the nodes of a tree T as we visitthem in this way, is called the level numbering ofnodes of T .
-
8/12/2019 Lect 8 Trees.pptx
27/48
33
Binary Trees
A B inary tree is an ordered tree with the following properties:
1. Every node has at most two children
2. Each child node is labeled as being either a lef t chi ld ora r ight chil d .
3. A lef t chi ld precedes a r ight chil d in the ordering ofchildren of a node, (Children form an ordered pair ).
A Binary tree is called proper if each node has either0 or 2 children. (also, called full Binary tree)
A Binary tree that is not proper, is improper .
-
8/12/2019 Lect 8 Trees.pptx
28/48
Trees
34
Binary Trees
Recursive definition:a Binary tree is either:
a tree consisting of asingle node, ora tree whose root has anordered pair of children,each of which is a Binarytree
Applications:arithmetic expressionsdecision processessearching
A
B C
F GD E
H I
-
8/12/2019 Lect 8 Trees.pptx
29/48
Trees
35
Arithmetic Expression Tree
Binary tree associated with an arithmetic expression internal nodes : contain operators (+, - , *, /, log, etc.)
external nodes : contain operands (variables or constants)
Example: arithmetic expression tree for the expression(2 (a - 1) + (3 b))
+
-2
a 1
3 b
-
8/12/2019 Lect 8 Trees.pptx
30/48
Trees
36
Decision Tree
Binary tree associated with a decision process internal nodes : questions with yes/no answer external nodes : decisions
Example: dining decision
Want a fast meal?
How about coffee? On expense account?
Starbucks Spikes Al Forno Caf Paragon
Yes No
Yes No Yes No
-
8/12/2019 Lect 8 Trees.pptx
31/48
Trees 37
Binary Tree ADT
The Binary Tree ADT extends the Tree ADT, i.e.,it inherits all the methods of the Tree ADT,Binary tree ADT supports the following additional
accessor methods:
position left(p) : return the left child of p , an errorcondition occurs if p has no left child.
position right(p) : return the right child of p, an errorcondition occurs if p has no right child. boolean hasLeft(p) : test whether p has a left child boolean hasRight(p) : test whether p has a right child
-
8/12/2019 Lect 8 Trees.pptx
32/48
Trees
38
Binary Tree ADT (Cont.)
Update methods may be defined by data structuresimplementing the Binary Tree ADT.Since Binary trees are ordered trees, the iterable
collection returned by method chilrden(p) (inherited from the Tree ADT), stores the left child of p before the right child of p.
-
8/12/2019 Lect 8 Trees.pptx
33/48
39
Properties of Proper Binary Trees
Notationn number of nodese number of external nodesi number of internal nodes
h heightb number of branches (edges)
Properties e = i + 1n = 2e - 1h i
h (n - 1) /2
-
8/12/2019 Lect 8 Trees.pptx
34/48
Trees
40
Minimum Number Of Nodes
Minimum number of nodes in a binary treewhose height is h, is n h+1 .At least one node at each of the d levels .
minimum number ofnodes is h+1
-
8/12/2019 Lect 8 Trees.pptx
35/48
Trees
41
Level 1 2 nodes
Level 2 4 nodes
Level 3 8 nodes
Level 0 1 node
Maximum Number Of Nodes
Max. number of nodes = 1 + 2 + 4 + 8 + + 2h
n 2h+1 - 1
-
8/12/2019 Lect 8 Trees.pptx
36/48
Trees
42
Full Binary Tree
A full Binary tree of a given height h has 2 h+1 1 nodes.
Height 3 full Binary tree.
-
8/12/2019 Lect 8 Trees.pptx
37/48
Binary Tree representation
1. Linked Structure2. Array List
-
8/12/2019 Lect 8 Trees.pptx
38/48
Trees
44
Linked Structure for Trees
A node is represented by anobject storing
ElementParent nodeSequence of children nodes
Node objects implement thePosition ADT
B
D A
C E
F
B
A D F
C
E
-
8/12/2019 Lect 8 Trees.pptx
39/48
Trees
45
A Linked Structure for Binary Trees
A node is represented by anobject storing
ElementParent nodeLeft child nodeRight child node
Node objects implement thePosition ADT
B
D A
C E
B
A D
C E
-
8/12/2019 Lect 8 Trees.pptx
40/48
Trees
46
Array-List Representation of Binary Trees
An alternative representation of a Binary tree is based onthe way of level numbering the nodes of T.
Nodes are stored in an array
For each node v of T, let p(v) be an integer defined as follows:If node v is the root, then p(v) = 1if node v is the left child of node u, then p(v) = 2* p(u)if node v is the right child of node u, than p(v) = 2* p(u)+1
The function p is known as a level numbering of nodes of T.
This level numbering suggests an implementation of a Binary Tree, T, by means ofan array list S such that node v of T is the element of S at index p(v). We realizearray list S by means of an extendable array.
-
8/12/2019 Lect 8 Trees.pptx
41/48
Trees
47
Example
The figure below is an example of a Binary tree and itslevel numbering .
Note that some numbers are skipped through numbering
process, e.g., numbers 8 & 9.
+
-2
a 1
3 b
7654
32
1
1110
-
8/12/2019 Lect 8 Trees.pptx
42/48
Trees
48
Array Representation
tree[]0 5 10
a b c d e f g h i j
b
a
c
d e f g
h i j
1
2 3
4 5 6 7
8 9 10
k11
k
-
8/12/2019 Lect 8 Trees.pptx
43/48
Trees
49
Array-List Representation of Binary Trees
nodes are stored in an array:
This is a simple and efficient implementation.We can easily perform the methods root, parent,
left, right, hasLeft, hasRight, isInternal, isExternal,and isRoot by using simple arithmetic operationson the number p(v), associated with each node vinvolved in the operation.
1
2 3
6 74 5
10 11
A
HG
FE
D
C
B
J
-
8/12/2019 Lect 8 Trees.pptx
44/48
Binary Tree Traversal
1. Preorder2. Postorder3. Inorder4. Euler Tour
-
8/12/2019 Lect 8 Trees.pptx
45/48
Trees
51
1. PreOrder Traversal
Algorithm binaryPreOrder(T,v)visit(v)if hasLeft (v) then
binaryPreOrder (T,left (v))if hasRight (v)
binaryPreOrder(T,right (v))
5
3
2
6
1
8 9
7
4
-
8/12/2019 Lect 8 Trees.pptx
46/48
Trees
52
2. PostOrder Traversal
Algorithm binaryPostOrder(T,v)if hasLeft (v) then
binaryPostOrder (T,left (v))if hasRight (v)
binaryPostOrder(T,right (v))
visit(v)
2
1
5
3
9
6 7
8
4
-
8/12/2019 Lect 8 Trees.pptx
47/48
Trees
53
3. Inorder Traversal
In an inorder traversal a nodeis visited after its left subtreeand before its right subtreeApplication: draw a binarytree
x(v) = inorder rank of vy(v) = depth of v
Algorithm inOrder(T,v)if hasLeft (v) then
inOrder (T,left (v))visit(v)if hasRight (v)
inOrder (T,right (v))
3
1
2
5
6
7 9
8
4
-
8/12/2019 Lect 8 Trees.pptx
48/48
Questions