# Dollar Tree Print Application - PowerPoint by pbd53851

VIEWS: 47 PAGES: 24

• pg 1
```									  Trees
Make Money Fast!

Stock            Ponzi       Bank
Fraud           Scheme      Robbery

1/20/2011 4:18 PM           Trees                         1
Outline and Reading
Tree ADT (§2.3.1)
Preorder and postorder traversals (§2.3.2)
BinaryTree ADT (§2.3.3)
Inorder traversal (§2.3.3)
Euler Tour traversal (§2.3.3)
Template method pattern
Data structures for trees (§2.3.4)
Java implementation (http://jdsl.org)

1/20/2011 4:18 PM       Trees                     2
What is a Tree
In computer science, a
tree is an abstract model                        Computers”R”Us
of a hierarchical
structure
A tree consists of nodes          Sales                   Manufacturing       R&D
with a parent-child
relation
US         International     Laptops    Desktops
Applications:
   Organization charts
   File systems        Europe           Asia        Canada
   Programming
environments

1/20/2011 4:18 PM                  Trees                                      3
Tree Terminology
Root: node without parent (A)                Subtree: tree consisting of
Internal node: node with at least            a node and its
one child (A, B, C, F)                       descendants
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
grandchild, grand-grandchild, etc.                           subtree

1/20/2011 4:18 PM                Trees                                       4
Tree ADT
We use positions to abstract                Query methods:
nodes                                          boolean isInternal(p)
Generic methods:                               boolean isExternal(p)
   integer size()                            boolean isRoot(p)
   boolean isEmpty()                      Update methods:
   objectIterator elements()                 swapElements(p, q)
   positionIterator positions()              object replaceElement(p, o)
Accessor methods:                           Additional update methods
   position root()                        may be defined by data
   position parent(p)                     structures implementing the
   positionIterator children(p)           Tree ADT

1/20/2011 4:18 PM                        Trees                                5
Preorder Traversal
A traversal visits the nodes of a                Algorithm preOrder(v)
tree in a systematic manner
visit(v)
In a preorder traversal, a node is
visited before its descendants                      for each child w of v
Application: print a structured                         preorder (w)
document
1
Make Money Fast!

2                                     5                           9
1. Motivations                                 2. Methods          References

6                 7             8
3                    4
2.1 Stock        2.2 Ponzi    2.3 Bank
1.1 Greed          1.2 Avidity
Fraud          Scheme       Robbery

1/20/2011 4:18 PM                          Trees                                   6
Postorder Traversal
In a postorder traversal, a              Algorithm postOrder(v)
node is visited after its
descendants                                 for each child w of v
Application: compute space                      postOrder (w)
used by files in a directory and            visit(v)
its subdirectories
9
cs16/

8
3                                7
todo.txt
homeworks/                                programs/
1K

1                  2       4                    5               6
h1c.doc           h1nc.doc   DDR.java           Stocks.java   Robot.java
3K                 2K        10K                 25K           20K

1/20/2011 4:18 PM                  Trees                                         7
Amortized Analysis of
Tree Traversal
Time taken in preorder or postorder traversal
of an n-node tree is proportional to the sum,
taken over each node v in the tree, of the
time needed for the recursive call for v.
   The call for v costs \$(cv + 1), where cv is the
number of children of v
   For the call for v, charge one cyber-dollar to v and
charge one cyber-dollar to each child of v.
   Each node (except the root) gets charged twice:
once for its own call and once for its parent’s call.
   Therefore, traversal time is O(n).
1/20/2011 4:18 PM             Trees                             8
Binary Trees
A binary tree is a tree with the                Applications:
following properties:                               arithmetic expressions
   Each internal node has two                     decision processes
children
   searching
   The children of a node are an
ordered pair                                                A
We call the children of an internal
node left child and right child
Alternative recursive definition: a              B                       C
binary tree is either
   a tree consisting of a single node,
or
D            E           F           G
   a tree whose root has an ordered
pair of children, each of which is a
binary tree
H       I

1/20/2011 4:18 PM                    Trees                                        9
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           -               3       b

a        1

1/20/2011 4:18 PM                   Trees                   10
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?
Yes                             No

How about coffee?                On expense account?
Yes             No              Yes               No

Starbucks         Spike’s           Al Forno        Café Paragon

1/20/2011 4:18 PM                 Trees                             11
Properties of Binary Trees
Notation                        Properties:
n number of nodes                e = i + 1
e number of
 n = 2e - 1
external nodes
 h  i
i number of internal
nodes                          h  (n - 1)/2
h height                         e  2
h

 h  log2 e

 h  log2 (n + 1) - 1

1/20/2011 4:18 PM            Trees                      12
BinaryTree ADT
The BinaryTree ADT               Update methods
extends the Tree                 may be defined by
ADT, i.e., it inherits           data structures
all the methods of               implementing the
the Tree ADT                     BinaryTree ADT
Additional methods:
   position leftChild(p)
   position rightChild(p)
   position sibling(p)

1/20/2011 4:18 PM             Trees                       13
Inorder Traversal
In an inorder traversal a            Algorithm inOrder(v)
node is visited after its left
subtree and before its right            if isInternal (v)
subtree                                      inOrder (leftChild (v))
Application: draw a binary              visit(v)
tree
   x(v) = inorder rank of v           if isInternal (v)
y(v) = depth of v                       inOrder (rightChild (v))

6

2                       8

1              4       7           9

3       5

1/20/2011 4:18 PM                   Trees                           14
Print Arithmetic Expressions
Specialization of an inorder                Algorithm printExpression(v)
traversal
   print operand or operator
if isInternal (v)
when visiting node                             print(“(’’)
   print “(“ before traversing left
subtree
inOrder (leftChild (v))
   print “)“ after traversing right          print(v.element ())
subtree
if isInternal (v)
+                                inOrder (rightChild (v))
                                                  print (“)’’)

2            -             3        b
((2  (a - 1)) + (3  b))
a         1
1/20/2011 4:18 PM                            Trees                           15
Evaluate Arithmetic Expressions
Specialization of a postorder           Algorithm evalExpr(v)
traversal                                   if isExternal (v)
   recursive method returning                  return v.element ()
the value of a subtree                 else
   when visiting an internal                   x  evalExpr(leftChild (v))
node, combine the values
y  evalExpr(rightChild (v))
of the subtrees
  operator stored at v
+                        return x  y

                          

2              -           3       2

5          1
1/20/2011 4:18 PM                       Trees                                16
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      R                           
B
2                     -             3       2

5           1

1/20/2011 4:18 PM                        Trees                           17
Template Method Pattern
Generic algorithm that    public abstract class EulerTour {
can be specialized by       protected BinaryTree tree;
redefining certain steps    protected void visitExternal(Position p, Result r) { }
Implemented by means of     protected void visitLeft(Position p, Result r) { }
an abstract Java class      protected void visitBelow(Position p, Result r) { }
protected void visitRight(Position p, Result r) { }
Visit methods that can be   protected Object eulerTour(Position p) {
redefined by subclasses         Result r = new Result();
Template method eulerTour       if tree.isExternal(p) { visitExternal(p, r); }
   Recursively called on the              else {
left and right children                   visitLeft(p, r);
   A Result object with fields               r.leftResult = eulerTour(tree.leftChild(p));
leftResult, rightResult and               visitBelow(p, r);
finalResult keeps track of                r.rightResult = eulerTour(tree.rightChild(p));
the output of the                         visitRight(p, r);
recursive calls to eulerTour
return r.finalResult;
}…
1/20/2011 4:18 PM                      Trees                                             18
Specializations of EulerTour
We show how to                       public class EvaluateExpression
specialize class                                      extends EulerTour {
EulerTour to evaluate                    protected void visitExternal(Position p, Result r) {
an arithmetic                               r.finalResult = (Integer) p.element();
expression                               }
Assumptions                              protected void visitRight(Position p, Result r) {
   External nodes store                  Operator op = (Operator) p.element();
Integer objects                       r.finalResult = op.operation(
(Integer) r.leftResult,
   Internal nodes store
(Integer) r.rightResult
Operator objects
);
supporting method
}
operation (Integer, Integer)
…
}

1/20/2011 4:18 PM                            Trees                                              19
Data Structure for Trees
A node is represented by
an object storing                    
   Element
   Parent node
   Sequence of children       B
nodes
Node objects implement                                                  
the Position ADT
A           D       F
B

A              D           F

C          E                                               
C           E
1/20/2011 4:18 PM                       Trees                           20
Data Structure for Binary Trees
A node is represented
by an object storing                         
   Element
   Parent node
   Left child node                        B
   Right child node
Node objects implement                  
the Position ADT

B                A                  D

A                  D                                         

C           E               C               E

1/20/2011 4:18 PM                   Trees                           21
Array-Based Representation of
Binary Trees
nodes are stored in an array
1
A
…
2                                 3
B                        D

   let rank(node) be defined as follows:
   rank(root) = 1                              4                    5       6                     7
E            F                C            J
   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                   11
rank(node) = 2*rank(parent(node))+1
G           H
1/20/2011 4:18 PM                     Trees                                                       22
Java Implementation
Tree interface                                 expandExternal(v)
BinaryTree interface
extending Tree                         v                                   v
A
Classes implementing Tree          A
and BinaryTree and
           
providing
   Constructors
   Update methods
removeAboveExternal(w)
   Print methods
Examples of updates for
binary trees                               A                           B
   expandExternal(v)                              w
   removeAboveExternal(w)     B               C

1/20/2011 4:18 PM                 Trees                                       23
Trees in JDSL
JDSL is the Library of Data             JDSL was developed at
Structures in Java                      Brown’s Center for Geometric
Tree interfaces in JDSL                 Computing
   InspectableBinaryTree              See the JDSL documentation
   InspectableTree                    and tutorials at http://jdsl.org
   BinaryTree
InspectableTree
   Tree
Inspectable versions of the
interfaces do not have
Tree
update methods
Tree classes in JDSL           InspectableBinaryTree

   NodeBinaryTree
   NodeTree
BinaryTree

1/20/2011 4:18 PM                  Trees                                   24

```
To top