trees1 make money fast! stock fraud ponzi scheme bank robbery © 2010 goodrich, tamassia
TRANSCRIPT
Trees 1
Trees
Make Money Fast!
StockFraud
PonziScheme
BankRobbery
© 2010 Goodrich, Tamassia
Trees 2
What is a Tree In computer science,
a tree is an abstract model of a hierarchical structure
A tree consists of nodes with a parent-child relation
Applications: Organization charts File systems Programming
environments
Computers”R”Us
Sales R&DManufacturing
Laptops DesktopsUS International
Europe Asia Canada
© 2010 Goodrich, Tamassia
Trees 3subtree
Tree Terminology Root: node without parent (A) Internal node: node with at least
one child (A, B, C, F) External node (a.k.a. leaf ):
node without children (E, I, J, K, G, H, D)
Ancestors of a node: parent, grandparent, grand-grandparent, etc.
Depth of a node: number of ancestors
Height of a tree: maximum depth of an external node (3)
Descendant of a node: child, grandchild, grand-grandchild, etc.
A
B DC
G HE F
I J K
Subtree: tree consisting of a node and its descendants
© 2010 Goodrich, Tamassia
4
More TerminologyTrees (Goodrich, 268)
Siblings = two or more nodes that are children of the same parent
Subtree rooted at v
vv
Internal node = node with one or more childrenExternal node = node with no childrenLeaf = external node
Trees 5
Tree ADT We use positions to
abstract nodes Generic methods:
integer size() boolean isEmpty() Iterator iterator() Iterable positions()
Accessor methods: position root() position parent(p) Iterable children(p)
Query methods: boolean isInternal(p) boolean isExternal(p) boolean isRoot(p)
Update method: element replace (p, o)
Additional update methods may be defined by data structures implementing the Tree ADT
© 2010 Goodrich, Tamassia
6
Tree Interface
public interface Tree<E> {
public int size();
public boolean isEmpty();
public Iterator<E> iterator();
public Iterable<Position<E>> positions();
public E replace(Position<E> v, E e)throws InvalidPositionException;
public Position<E> root() throws EmptyTreeException;
public Position<E> parent(Position<E> v)throws InvalidPositionException, BoundaryViolationException;
public Iterable<Position<E>> children(Position<E> v) throws InvalidPositionException;
public boolean isInternal(Position<E> v) throws InvalidPositionException;
public boolean isExternal(Position<E> v) throws InvalidPositionException;
public boolean isRoot(Position<E> v)throws InvalidPositionException;
}
Trees (Goodrich, 270)
7
Running Time AssumptionsTrees (Goodrich, 272)
O(n)iterator, positions
O(1)replace
O(1)swapElementsO(cv) (cv = no. of children of v)children
O(1)isRoot
O(1)isInternal, isExternal
O(1)parent
O(1)root
TimeMethod
8
Depth of a Node in a Tree
Depth of v = number of ancestors of v• If v is the root, v’s depth = 0• Else, v’s depth = 1 + depth of v’s parent
Trees (Goodrich, 273)
Depth
0
1 + depth( myParent ) = 1 + 0 = 1
1 + depth( myParent ) = 1 + 1 = 2
1 + depth( myParent ) = 1 + 2 = 3
9
Finding the Depth
Algorithm depth( T, v ) if T.isRoot(v) then return 0 else return 1 + depth( T, T.parent(v) )
Trees (Goodrich, 273)
10
Finding the Depth
Algorithm depth( T, v ) if T.isRoot(v) then return 0 else return 1 + depth( T, T.parent(v) )
Trees (Goodrich, 273)
public static <E> int depth(Tree<E> T, Position<E> v){ if( T.isRoot(v) ) return 0; else return 1 + depth( T, T.parent(v) );}
11
Height
Height of node v• If v is an external node, v’s height = 0• Else, v’s height = 1 + maximum height of v’s children
Trees (Goodrich, 274–275)
v
hv = 1 + max( h of myChildren ) hv = 1 + 1 = 2
h = 0 (External node)
h = 1 + max( h of myChildren )h = 1 + 0 = 1
h = 0 (External node)
12
Height
Height of node v• If v is an external node, v’s height = 0• Else, v’s height = 1 + maximum height of v’s children
Trees (Goodrich, 274–275)
v
hv = 1 + max( h of myChildren ) hv = 1 + 1 = 2
h = 0 (External node)
Height of tree T• T’s height = height of the root of T
h = 1 + max( h of myChildren )h = 1 + 0 = 1
h = 0 (External node)
13
Finding the Height of a Tree
Algorithm height( T, root ) if T.isExternal(root) then return 0 else h = 0 for each node T.children(root) do h = max( h, height(T,node) ) return 1 + h r
u
t
vh = 0h = max(h,height(T,t))return 1 + h
r 0 0
1
2
T
Trees (Goodrich, 274–275)
14
Finding the Height of a Tree
Algorithm height( T, root ) if T.isExternal(root) then return 0 else h = 0 for each node T.children(root) do h = max( h, height(T,node) ) return 1 + h r
u
t
vh = 0h = max(h,height(T,t))return 1 + h
r 0 0
1
2
h = 0h = max(h,height(T,u))h = max(h,height(T,v))return 1 + h
t
T
Trees (Goodrich, 274–275)
15
Finding the Height of a Tree
Algorithm height( T, root ) if T.isExternal(root) then return 0 else h = 0 for each node T.children(root) do h = max( h, height(T,node) ) return 1 + h r
u
t
vh = 0h = max(h,height(T,t))return 1 + h
r 0 0
1
2
h = 0h = max(h,height(T,u))h = max(h,height(T,v))return 1 + h
t
return 0
return 0u
T
Trees (Goodrich, 274–275)
16
Finding the Height of a Tree
Algorithm height( T, root ) if T.isExternal(root) then return 0 else h = 0 for each node T.children(root) do h = max( h, height(T,node) ) return 1 + h r
u
t
vh = 0h = max(h,height(T,t))return 1 + h
r 0 0
1
2
h = 0h = max(h,height(T,u))h = max(h,height(T,v))return 1 + h
t
return 0 return 0
return 0ureturn 0v
T
Trees (Goodrich, 274–275)
17
Finding the Height of a Tree
Algorithm height( T, root ) if T.isExternal(root) then return 0 else h = 0 for each node T.children(root) do h = max( h, height(T,node) ) return 1 + h r
u
t
vh = 0h = max(h,height(T,t))return 1 + h
r 0 0
1
2
h = 0h = max(h,height(T,u))h = max(h,height(T,v))return 1 + h
t
return 0
return 0u
T
Trees (Goodrich, 274–275)
return 0
return 0v
return 1
18
Finding the Height of a Tree
Algorithm height( T, root ) if T.isExternal(root) then return 0 else h = 0 for each node T.children(root) do h = max( h, height(T,node) ) return 1 + h r
u
t
vh = 0h = max(h,height(T,t))return 1 + h
r 0 0
1
2
return 1
return 2
h = 0h = max(h,height(T,u))h = max(h,height(T,v))return 1 + h
t
return 0 return 0
return 0ureturn 0v
T
Trees (Goodrich, 274–275)
Trees 19
Preorder Traversal A traversal visits the nodes of
a tree in a systematic manner In a preorder traversal, a
node is visited before its descendants
Application: print a structured document
Make Money Fast!
1. Motivations References2. Methods
2.1 StockFraud
2.2 PonziScheme
1.1 Greed 1.2 Avidity2.3 BankRobbery
1
2
3
5
4 6 7 8
9
Algorithm preOrder(v)visit(v)for each child w of v
preorder (w)
© 2010 Goodrich, Tamassia
Trees 20
Postorder Traversal In a postorder traversal, a
node is visited after its descendants
Application: compute space used by files in a directory and its subdirectories
Algorithm postOrder(v)for each child w of v
postOrder (w)visit(v)
cs16/
homeworks/todo.txt
1Kprograms/
DDR.java10K
Stocks.java25K
h1c.doc3K
h1nc.doc2K
Robot.java20K
9
3
1
7
2 4 5 6
8
© 2010 Goodrich, Tamassia
Trees 21
Binary Trees A binary tree is a tree with the
following properties: Each internal node has at most
two children (exactly two for proper binary trees)
The children of a node are an ordered pair
We call the children of an internal node left child and right child
Alternative recursive definition: a binary tree is either
a tree consisting of a single node, or
a tree whose root has an ordered pair of children, each of which is a binary tree
Applications: arithmetic
expressions decision processes searching
A
B C
F GD E
H I© 2010 Goodrich, Tamassia
Trees 22
Arithmetic Expression Tree Binary tree associated with an arithmetic expression
internal nodes: operators external nodes: operands
Example: arithmetic expression tree for the expression (2 (a 1) (3 b))
2
a 1
3 b
© 2010 Goodrich, Tamassia
Trees 23
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 Spike’s Al Forno Café Paragon
Yes No
Yes No Yes No
© 2010 Goodrich, Tamassia
Trees 24
Properties of Proper Binary Trees
Notationn number of nodese number of
external nodesi number of
internal nodesh height
Properties: e i 1 n 2e 1 h i h (n 1)2 e 2h
h log2 e
h log2 (n 1) 1
© 2010 Goodrich, Tamassia
Level d has at most 2d nodes
© 2010 Goodrich, Tamassia Trees 25
Trees 26
BinaryTree ADT
The BinaryTree ADT extends the Tree ADT, i.e., it inherits all the methods of the Tree ADT
Additional methods: position left(p) position right(p) boolean hasLeft(p) boolean hasRight(p)
Update methods may be defined by data structures implementing the BinaryTree ADT
© 2010 Goodrich, Tamassia
Trees 27
Inorder Traversal In an inorder traversal a
node is visited after its left subtree and before its right subtree
Application: draw a binary tree
x(v) = inorder rank of v y(v) = depth of v
Algorithm inOrder(v)if hasLeft (v)
inOrder (left (v))visit(v)if hasRight (v)
inOrder (right (v))
3
1
2
5
6
7 9
8
4
© 2010 Goodrich, Tamassia
Trees 28
Print Arithmetic Expressions
Specialization of an inorder traversal
print operand or operator when visiting node
print “(“ before traversing left subtree
print “)“ after traversing right subtree
Algorithm printExpression(v)if hasLeft (v)
print(“(’’)inOrder (left(v))
print(v.element ())if hasRight (v)
inOrder (right(v))print (“)’’)
2
a 1
3 b((2 (a 1)) (3 b))
© 2010 Goodrich, Tamassia
Trees 29
Evaluate Arithmetic Expressions
Specialization of a postorder traversal
recursive method returning the value of a subtree
when visiting an internal node, combine the values of the subtrees
Algorithm evalExpr(v)if isExternal (v)
return v.element ()else
x evalExpr(leftChild (v))
y evalExpr(rightChild (v))
operator stored at vreturn x y
2
5 1
3 2
© 2010 Goodrich, Tamassia
Trees 30
Euler Tour Traversal Generic traversal of a binary tree Includes a special cases the preorder, postorder and inorder
traversals Walk around the tree and visit each node three times:
on the left (preorder) from below (inorder) on the right (postorder)
2
5 1
3 2
LB
R
© 2010 Goodrich, Tamassia
Trees 31
Linked Structure for Trees A node is represented
by an object storing Element Parent node Sequence of children
nodes Node objects implement
the Position ADT
B
DA
C E
F
B
A D F
C
E© 2010 Goodrich, Tamassia
Trees 32
Linked Structure for Binary Trees A node is represented
by an object storing Element Parent node Left child node Right child node
Node objects implement the Position ADT
B
DA
C E
B
A D
C E
© 2010 Goodrich, Tamassia
Array-Based Representation of Binary Trees
Nodes are stored in an array A
© 2010 Goodrich, Tamassia 33Trees
Node v is stored at A[rank(v)] rank(root) = 1 if node is the left child of parent(node),
rank(node) = 2 rank(parent(node))
if node is the right child of parent(node), rank(node) = 2
rank(parent(node)) 1
1
2 3
6 74 5
10 11
A
HG
FE
D
C
B
J
A B D G H ……
1 2 3 10 110
34
Implementing a Binary Tree
35
Linked Binary Tree
Natural way to represent a tree is by using linked nodes
Trees (Goodrich, 287–295)
36
Node for a Binary Tree
leftelement
parentright
Trees (Goodrich, 287–295)
37
Node for a Binary Tree
leftelement
parentright
leftr
nullright
nulls
parentnull null
t
parentnull
root
Trees (Goodrich, 287–295)
38
Node for a Binary Tree
public class BTNode<E> implements BTPosition { private E element; public BTNode() { } public BTNode(E element, BTPosition<E> parent,
BTPosition<E> left, BTPosition<E> right) { setElement(element); setParent(parent); setLeft(left); setRight(right); } public E element() { return element; } public void setElement(E o) { element=o; } public BTPosition<E> getLeft() { return left; } public void setLeft(BTPosition<E> v) { left=v; } public BTPosition<E> getRight() { return right; } public void setRight(BTPosition<E> v) { right=v; } public BTPosition<E> getParent() { return parent; } public void setParent(BTPosition<E> v) { parent=v; }}
Trees (Goodrich, 287–295)
39
Position for a Binary Tree
public interface BTPosition<E> extends Position<E>{// inherits element()
public void setElement(E o); public BTPosition<E> getLeft(); public void setLeft(BTPosition<E> v); public BTPosition<E> getRight(); public void setRight(BTPosition<E> v); public BTPosition<E> getParent(); public void setParent(BTPosition<E> v);}
Trees (Goodrich, 287–295)
40
A Position Interface
public interface Position<E> {
/** Return the element stored at this position. */
E element();
}
A Position object, has only one operation that it can use. This operation returns the element stored inside the object.
Positions (Goodrich, 232, 234)
41
Some Operations of a Binary TreeReturn to pages 304 - 308
public class LinkedBinaryTree<E> implements BinaryTree<E> { public int size() {return size; } public boolean isEmpty() { /*...*/ } public boolean isInternal(Position<E> v) throws InvalidPositionException { checkPosition(v); return (hasLeft(v) || hasRight(v)); } public boolean isExternal(Position<E> v) throws InvalidPositionException { /*...*/ } public boolean isRoot(Position<E> v) throws InvalidPositionException { checkPosition(v); return (v == root()); } public boolean hasLeft(Position<E> v) throws InvalidPositionException { BTPosition<E> vv = checkPosition(v); return (vv.getLeft() != null); } public boolean hasRight(Position<E> v) throws InvalidPositionException { /*...*/ } public Position<E> root() throws EmptyTreeException { /*...*/ } public Position<E> left(Position<E> v) throws InvalidPositionException, BoundaryViolationException { BTPosition<E> vv = checkPosition(v); Position<E> leftPos = vv.getLeft(); if (leftPos == null) throw new BoundaryViolationException(); return leftPos;} public Position<E> right(Position<E> v) throws InvalidPositionException, BoundaryViolationException { /*...*/ }
Trees (Goodrich, 287–295)
42
Instance Variablesof a Binary Tree
public class LinkedBinaryTree<E> implements BinaryTree<E> { protected BTPosition<E> root; // reference to the root protected int size; // number of nodes
//...
Trees (Goodrich, 287–295)
43
Constructor of a Binary Tree
public class LinkedBinaryTree<E> implements BinaryTree<E> { protected BTPosition<E> root; // reference to the root protected int size; // number of nodes
public LinkedBinaryTree() { root = null; // start with an empty tree size = 0; }
//...
Trees (Goodrich, 287–295)
44
Operations of the LinkedBinaryTree
Tell us about the positionspos root()pos parent( pos )iter children( pos )bool isInternal( pos )bool isExternal( pos )bool isRoot( pos )pos left( pos )pos right( pos )pos hasLeft( pos )pos hasRight( pos )pos sibling( pos )
Tell us about the collectionint size()bool isEmpty()iter iterator()iter positions()
Update the datavoid replace( pos, e )addRoot( e )insertLeft( pos, e )insertRight( pos, e )remove( pos )
Trees (Goodrich, 289–295)
Tree methodsBinary Tree methodsAdditional methods
45
Adding an Element to a LinkedBinaryTree Object
LinkedBinaryTree<Character> T = new LinkedBinaryTree<Character>;
Creates an empty tree.
Trees (Goodrich, 287–295)
root
AT.addRoot(new Character('A')); Adds a node as root and fills it with an element.
root
46
Adding an Element to a LinkedBinaryTree Object
LinkedBinaryTree<Character> T = new LinkedBinaryTree<Character>;
Creates an empty tree.
Trees (Goodrich, 287–295)
root
AT.addRoot(new Character('A')); Adds a node as root and fills it with an element.
root
AT.insertLeft( T.root(), new Character('B'));
Inserts the node with its element.
B
root
47
An Alternative Binary Tree Implementation
ArrayList Implementation
48
Binary TreeImplemented with an ArrayList
While it’s natural to think of implementing a tree with linked Nodes, a binary tree can also be implemented with an ArrayList
Advantage: better performance
Trees (Goodrich, 296–297)
49
Binary TreeImplemented as an ArrayList
Based on a way of numbering the nodes• If v is the root of T, then p(v) = 1• If v is the left child of node u, then p(v) = 2 * p(u)• If v is the right child of node u, then p(v) = 2 * p(u) + 1
Trees (Goodrich, 289–291)
D
E
F
GA C
B
1
2 3
4 5 6 7
D B F A C E G
0 1 2 3 4 5 6 7 8 9A