make money fast!

Post on 12-Sep-2021

10 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1/18/2005 4:17 AM Trees 1

Trees

Make Money Fast!

StockFraud

PonziScheme

BankRobbery

1/18/2005 4:17 AM Trees 2

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 patternData structures for trees (§2.3.4)Java implementation (http://jdsl.org)

1/18/2005 4:17 AM Trees 3

What is a TreeIn computer science, a tree is an abstract model of a hierarchical structureA tree consists of nodes with a parent-child relationApplications:

Organization chartsFile systemsProgramming environments

Computers”R”Us

Sales R&DManufacturing

Laptops DesktopsUS International

Europe Asia Canada

1/18/2005 4:17 AM Trees 4

subtree

Tree TerminologyRoot: 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 ancestorsHeight of a tree: maximum depth of any 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

1/18/2005 4:17 AM Trees 5

Tree ADTWe use positions to abstract nodesGeneric methods:

integer size()boolean isEmpty()objectIterator elements()positionIterator positions()

Accessor methods:position root()position parent(p)positionIterator children(p)

Query methods:boolean isInternal(p)boolean isExternal(p)boolean isRoot(p)

Update methods:swapElements(p, q)object replaceElement(p, o)

Additional update methods may be defined by data structures implementing the Tree ADT

1/18/2005 4:17 AM Trees 6

Preorder TraversalA traversal visits the nodes of a tree in a systematic mannerIn 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 PonziScheme1.1 Greed 1.2 Avidity 2.3 Bank

Robbery

1

2

3

5

4 6 7 8

9

Algorithm preOrder(v)visit(v)for each child w of v

preorder (w)

1/18/2005 4:17 AM Trees 7

Postorder TraversalIn a postorder traversal, a node is visited after its descendantsApplication: 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.txt1Kprograms/

DDR.java10K

Stocks.java25K

h1c.doc3K

h1nc.doc2K

Robot.java20K

9

3

1

7

2 4 5 6

8

1/18/2005 4:17 AM Trees 8

Binary TreeA binary tree is a tree with the following properties:

Each internal node has two childrenThe children of a node are an ordered pair

We call the children of an internal node left child and right childAlternative recursive definition: a binary tree is either

a tree consisting of a single node, ora tree whose root has an ordered pair of children, each of which is a binary tree

Applications:arithmetic expressionsdecision processessearching

A

B C

F GD E

H I

1/18/2005 4:17 AM Trees 9

Arithmetic Expression TreeBinary tree associated with an arithmetic expression

internal nodes: operatorsexternal nodes: operands

Example: arithmetic expression tree for the expression (2 × (a − 1) + (3 × b))

+

××

−2

a 1

3 b

1/18/2005 4:17 AM Trees 10

Decision TreeBinary tree associated with a decision process

internal nodes: questions with yes/no answerexternal 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

1/18/2005 4:17 AM Trees 11

Properties of Binary TreesNotationn number of nodese number of

external nodesi number of internal

nodesh height

Properties:e = i + 1n = 2e − 1h ≤ ih ≤ (n − 1)/2e ≤ 2h

h ≥ log2 eh ≥ log2 (n + 1) − 1

1/18/2005 4:17 AM Trees 12

BinaryTree ADT

The BinaryTree ADT extends the Tree ADT, i.e., it inherits all the methods of the Tree ADTAdditional methods:

position leftChild(p)position rightChild(p)position sibling(p)

Update methods may be defined by data structures implementing the BinaryTree ADT

1/18/2005 4:17 AM Trees 13

Inorder TraversalIn an inorder traversal a node is visited after its left subtree and before its right subtreeApplication: draw a binary tree

x(v) = inorder rank of vy(v) = depth of v

Algorithm inOrder(v)if isInternal (v)

inOrder (leftChild (v))visit(v)if isInternal (v)

inOrder (rightChild (v))

3

1

2

5

6

7 9

8

4

1/18/2005 4:17 AM Trees 14

Print Arithmetic ExpressionsSpecialization of an inorder traversal

print operand or operator when visiting nodeprint “(“ before traversing left subtreeprint “)“ after traversing right subtree

Algorithm printExpression(v)if isInternal (v)

print(“(’’)inOrder (leftChild (v))

print(v.element ())if isInternal (v)

inOrder (rightChild (v))print (“)’’)

+

××

−2

a 1

3 b((2 × (a − 1)) + (3 × b))

1/18/2005 4:17 AM Trees 15

Evaluate Arithmetic ExpressionsSpecialization of a postorder traversal

recursive method returning the value of a subtreewhen 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

1/18/2005 4:17 AM Trees 16

Euler Tour TraversalGeneric traversal of a binary treeIncludes a special cases the preorder, postorder and inorder traversalsWalk 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

1/18/2005 4:17 AM Trees 17

Template Method PatternGeneric algorithm that can be specialized by redefining certain stepsImplemented by means of an abstract Java class Visit methods that can be redefined by subclassesTemplate method eulerTour

Recursively called on the left and right childrenA Result object with fields leftResult, rightResult andfinalResult keeps track of the output of the recursive calls to eulerTour

public abstract class EulerTour {protected BinaryTree tree;protected void visitExternal(Position p, Result r) { }protected void visitLeft(Position p, Result r) { }protected void visitBelow(Position p, Result r) { }protected void visitRight(Position p, Result r) { }protected Object eulerTour(Position p) {

Result r = new Result();if tree.isExternal(p) { visitExternal(p, r); }

else {visitLeft(p, r);r.leftResult = eulerTour(tree.leftChild(p));visitBelow(p, r);r.rightResult = eulerTour(tree.rightChild(p));visitRight(p, r);return r.finalResult;

} …

1/18/2005 4:17 AM Trees 18

Specializations of EulerTourWe show how to specialize class EulerTour to evaluate an arithmetic expressionAssumptions

External nodes store Integer objectsInternal nodes store Operator objects supporting methodoperation (Integer, Integer)

public class EvaluateExpressionextends EulerTour {

protected void visitExternal(Position p, Result r) {r.finalResult = (Integer) p.element();

}

protected void visitRight(Position p, Result r) {Operator op = (Operator) p.element();r.finalResult = op.operation(

(Integer) r.leftResult,(Integer) r.rightResult);

}

}

1/18/2005 4:17 AM Trees 19

Data Structure for TreesA node is represented by an object storing

ElementParent nodeSequence of children nodes

Node objects implement the Position ADT

B

DA

C E

F

B

∅ ∅

A D F

∅C

∅E

1/18/2005 4:17 AM Trees 20

Data Structure for Binary TreesA node is represented by an object storing

ElementParent nodeLeft child nodeRight child node

Node objects implement the Position ADT

B

DA

C E

∅ ∅

∅ ∅ ∅ ∅

B

A D

C E

1/18/2005 4:17 AM Trees 21

Java ImplementationTree interfaceBinaryTree interface extending TreeClasses implementing Tree and BinaryTree and providing

ConstructorsUpdate methodsPrint methods

Examples of updates for binary trees

expandExternal(v)removeAboveExternal(w)

A

∅ ∅

expandExternal(v)

A

CB

B

removeAboveExternal(w)

Av v

w

1/18/2005 4:17 AM Trees 22

Trees in JDSLJDSL is the Library of Data Structures in JavaTree interfaces in JDSL

InspectableBinaryTreeInspectableTreeBinaryTreeTree

Inspectable versions of the interfaces do not have update methodsTree classes in JDSL

NodeBinaryTreeNodeTree

JDSL was developed at Brown’s Center for Geometric ComputingSee the JDSL documentation and tutorials at http://jdsl.org

InspectableTree

InspectableBinaryTree

Tree

BinaryTree

top related