Transcript ppt

Trees
Make Money Fast!
Stock
Fraud
© 2013 Goodrich, Tamassia, Goldwasser
Ponzi
Scheme
Trees
Bank
Robbery
1
Assignment #7: Linked Lists



C-7.29 Describe in detail an algorithm for reversing a singly linked list L using only a
constant amount of additional space and not using any recursion.
C-7.37 Implement a function that accepts a PositionalList L of n integers sorted in
nondecreasing order, and another value V, and determines in O(n) time if there are two
elements of L that sum precisely to V. The function should return a pair of positions of such
elements, if found, or None otherwise.
P-7.47 Implement a CardHand class that supports a person arranging a group of cards in
his or her hand. The simulator should represent the sequence of cards using a single
positional list ADT so that cards of the same suit are kept together. Implement this strategy
by means of four "fingers" into the hand, one for each of the suits of hearts, clubs, spades,
and diamonds, so that adding a new card to the person's hand or playing a correct card
from the hand can be done in constant time. The class should support the following
methods:

add_card(r, s): Add a new card with rank r and suit s to the hand.

play(s): Remove and return a card of suit s from the player's hand; if there is no card
of suit s, then remove and return an arbitrary card from the hand.

__iter__(): Iterate through all cards currently in the hand.

all_of_suit(s): Iterate through all cards of suit s that are currently in the hand.
2
C-7.19
C-7.37
P-7.47
P-7.47
General tree

Productivity experts say that breakthroughs
come by thinking “nonlinearly.”


referring to an organizational relationship that is
richer than the simple “before” and “after”
relationships between objects in sequences.
Tree structures allow us to implement a host
of algorithms much faster than when using
linear data structures, such as array-based
lists or linked lists.
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
US
Applications:



Computers”R”Us
Sales
International
Organization charts
File systems
Europe
Programming
environments
© 2013 Goodrich, Tamassia, Goldwasser
Manufacturing
Trees
Asia
Laptops
Desktops
Canada
9
R&D
Formal Tree Definition

define a tree T as a set of nodes storing
elements such that the nodes have a
parent-child relationship that satisfies the
following properties:


If T is nonempty, it has a special node, called the
root of T, that has no parent.
Each node v of T different from the root has a
unique parent node w; every node with parent w
is a child of w.
Define a tree recursively

a tree T is either empty or consists of a
node r, called the root of T, and a
(possibly empty) set of subtrees whose
roots are the children of r.
Tree Terminology







Root: node without parent (A)
 Subtree: tree consisting of
a node and its
Internal node: node with at least
descendants
one child (A, B, C, F)
External node (a.k.a. leaf ): node
A
without children (E, I, J, K, G, H, D)
Ancestors of a node: parent,
grandparent, grand-grandparent,
B
C
D
etc.
Depth of a node: number of
ancestors
E
F
G
H
Height of a tree: maximum depth
of any node (3)
Descendant of a node: child,
I
J
K
subtree
grandchild, grand-grandchild, etc.
© 2013 Goodrich, Tamassia, Goldwasser
Trees
12
Other Node Relationships

Two nodes that are children of the
same parent are siblings.
Edges and Paths in Trees


An edge of tree T is a pair of nodes
(u,v) such that u is the 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.

For example, the tree in Figure 8.3
contains the path (cs252/, projects/,
demos/, market).
preview of the remainder of this chapter
Ordered Trees




A tree is ordered if there is a meaningful linear order
among the children of each node;
A family tree that describes generational relationships
is often modeled as an ordered tree, with siblings
ordered according to their birth.
In contrast, an organizational chart for a company is
typically considered an unordered tree.
Likewise, when using a tree to describe an
inheritance hierarchy, there is no particular
significance to the order among the subclasses of a
parent class.
Tree ADT


We use positions to abstract
nodes
Generic methods:










Boolean is_leaf(p)
Boolean is_root(p)
element replace (p, o)
Additional update methods
may be defined by data
structures implementing the
Tree ADT
position root()
position parent(p)
Iterator children(p)
Integer num_children(p)
© 2013 Goodrich, Tamassia, Goldwasser

Update method:
Integer len()
Boolean is_empty()
Iterator positions()
Iterator iter()
Accessor methods:

Query methods:
Trees
17
Abstract Tree Class in Python
© 2013 Goodrich, Tamassia, Goldwasser
Trees
18
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
1
Algorithm preOrder(v)
visit(v)
for each child w of v
preorder (w)
Make Money Fast!
2
5
1. Motivations
9
2. Methods
3
4
1.1 Greed
1.2 Avidity
© 2013 Goodrich, Tamassia, Goldwasser
6
7
2.1 Stock
Fraud
Trees
2.2 Ponzi
Scheme
References
8
2.3 Bank
Robbery
19
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
9
Algorithm postOrder(v)
for each child w of v
postOrder (w)
visit(v)
cs16/
3
8
7
homeworks/
todo.txt
1K
programs/
1
2
h1c.doc
3K
h1nc.doc
2K
© 2013 Goodrich, Tamassia, Goldwasser
4
5
DDR.java
10K
Trees
Stocks.java
25K
6
Robot.java
20K
20
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



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
arithmetic expressions
decision processes
searching
A
We call the children of an internal
node left child and right child
Alternative recursive definition: a
binary tree is either

Applications:
B
C
D
E
H
© 2013 Goodrich, Tamassia, Goldwasser
Trees
F
I
21
G
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
© 2013 Goodrich, Tamassia, Goldwasser
3
b
1
Trees
22
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?
No
Yes
How about coffee?
On expense account?
Yes
No
Yes
No
Starbucks
Spike’s
Al Forno
Café Paragon
© 2013 Goodrich, Tamassia, Goldwasser
Trees
23
Properties of Proper Binary Trees

Notation
Properties:
 e = i + 1
 n = 2e - 1
 h  i
 h  (n - 1)/2
h
 e  2
 h  log2 e
 h  log2 (n + 1) - 1
n number of nodes
e number of
external nodes
i number of internal
nodes
h height
© 2013 Goodrich, Tamassia, Goldwasser
Trees
24
BinaryTree ADT


The BinaryTree ADT
extends the Tree
ADT, i.e., it inherits
all the methods of
the Tree ADT
Additional methods:




Update methods
may be defined by
data structures
implementing the
BinaryTree ADT
position left(p)
position right(p)
position sibling(p)
© 2013 Goodrich, Tamassia, Goldwasser
Trees
25
Inorder Traversal


In an inorder traversal a
node is visited after its left
subtree and before its right
subtree
Application: draw a binary
tree


Algorithm inOrder(v)
if v has a left child
inOrder (left (v))
visit(v)
if v has a right child
inOrder (right (v))
x(v) = inorder rank of v
y(v) = depth of v
6
2
8
1
4
3
© 2013 Goodrich, Tamassia, Goldwasser
7
9
5
Trees
26
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
+


-
2
a
3
Algorithm printExpression(v)
if v has a left child
print(“(’’)
inOrder (left(v))
print(v.element ())
if v has a right child
inOrder (right(v))
print (“)’’)
b
((2  (a - 1)) + (3  b))
1
© 2013 Goodrich, Tamassia, Goldwasser
Trees
27
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 is_leaf (v)
return v.element ()
else
x  evalExpr(left (v))
y  evalExpr(right (v))
  operator stored at v
return x  y

-
2
5
3
1
© 2013 Goodrich, Tamassia, Goldwasser
2
Trees
28
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)
+
L
2


R
B
5
© 2013 Goodrich, Tamassia, Goldwasser
3
2
1
Trees
29
Linked Structure for Trees

A node is represented by
an object storing




Element
Parent node
Sequence of children
nodes

B

Node objects implement
the Position ADT
A
B
D
A
C

D
F
F

E
© 2013 Goodrich, Tamassia, Goldwasser
Trees
C

30
E
Linked Structure for Binary Trees

A node is represented
by an object storing






Element
Parent node
Left child node
Right child node
B
Node objects implement
the Position ADT

B
A

A
D
C
© 2013 Goodrich, Tamassia, Goldwasser
D

E


C
Trees

E
31
Array-Based Representation of
Binary Trees

Nodes are stored in an array A
1
A
0

A
B
D
1
2
3
…
G
H
10
11
…
2
Node v is stored at A[rank(v)]
4
 rank(root) = 1
E
 if node is the left child of parent(node),
rank(node) = 2  rank(parent(node))
 if node is the right child of parent(node),
10
rank(node) = 2 rank(parent(node)) + 1
© 2013 Goodrich, Tamassia, Goldwasser
Trees
3
B
D
5
6
C
F
11
G
7
H
32
J