trees1 stacks (background). dr.alagoz trees2 applications of stacks direct applications page-visited...

40
Trees 1 Stacks (Background)

Upload: valentine-briggs

Post on 28-Dec-2015

216 views

Category:

Documents


1 download

TRANSCRIPT

Trees 1

Stacks (Background)

Trees 2Dr.Alagoz

Applications of Stacks

Direct applications Page-visited history in a Web browser Undo sequence in a text editor Chain of method calls in the Java

Virtual Machine

Indirect applications Auxiliary data structure for algorithms Component of other data structures

Trees 3Dr.Alagoz

Abstract Data Types (ADTs)

An abstract data type (ADT) is an abstraction of a data structureAn ADT specifies: Data stored Operations on

the data Error conditions

associated with operations

Example: ADT modeling a simple stock trading system The data stored are buy/sell

orders The operations supported are

order buy(stock, shares, price) order sell(stock, shares, price) void cancel(order)

Error conditions: Buy/sell a nonexistent stock Cancel a nonexistent order

Trees 4Dr.Alagoz

The Stack ADT The Stack ADT stores arbitrary objectsInsertions and deletions follow the last-in first-out schemeThink of a spring-loaded plate dispenserMain stack operations:

push(object): inserts an element

object pop(): removes and returns the last inserted element

Auxiliary stack operations:

object top(): returns the last inserted element without removing it

integer size(): returns the number of elements stored

boolean isEmpty(): indicates whether no elements are stored

Trees 5Dr.Alagoz

Stack Interface in Java

Java interface corresponding to our Stack ADTRequires the definition of class EmptyStackExceptionDifferent from the built-in Java class java.util.Stack

public interface Stack {

public int size();

public boolean isEmpty();

public Object top()throws EmptyStackException;

public void push(Object o);

public Object pop() throws EmptyStackException;

}

Trees 6Dr.Alagoz

ExceptionsAttempting the execution of an operation of ADT may sometimes cause an error condition, called an exceptionExceptions are said to be “thrown” by an operation that cannot be executed

In the Stack ADT, operations pop and top cannot be performed if the stack is emptyAttempting the execution of pop or top on an empty stack throws an EmptyStackException

Trees 7

Queues (Background)

Trees 8Dr.Alagoz

The Queue ADT The Queue ADT stores arbitrary objectsInsertions and deletions follow the first-in first-out schemeInsertions are at the rear of the queue and removals are at the front of the queueMain queue operations:

enqueue(object): inserts an element at the end of the queue

object dequeue(): removes and returns the element at the front of the queue

Auxiliary queue operations:

object front(): returns the element at the front without removing it

integer size(): returns the number of elements stored

boolean isEmpty(): indicates whether no elements are stored

Exceptions Attempting the execution

of dequeue or front on an empty queue throws an EmptyQueueException

Trees 9Dr.Alagoz

Applications of Queues

Direct applications Waiting lists, bureaucracy Access to shared resources (e.g.,

printer) Multiprogramming

Indirect applications Auxiliary data structure for algorithms Component of other data structures

Trees 10Dr.Alagoz

Array-based QueueUse an array of size N in a circular fashionTwo variables keep track of the front and rearf index of the front elementr index immediately past the rear element

Array location r is kept empty

Q0 1 2 rf

normal configuration

Q0 1 2 fr

wrapped-around configuration

Trees 11Dr.Alagoz

Queue OperationsWe use the modulo operator (remainder of division)

Algorithm size()return (N f + r) mod N

Algorithm isEmpty()return (f r)

Q0 1 2 rf

Q0 1 2 fr

Trees 12Dr.Alagoz

Queue Operations (cont.)Algorithm enqueue(o)

if size() = N 1 thenthrow FullQueueException

else Q[r] or (r + 1) mod N

Operation enqueue throws an exception if the array is fullThis exception is implementation-dependent

Q0 1 2 rf

Q0 1 2 fr

Trees 13Dr.Alagoz

Queue Operations (cont.)Operation dequeue throws an exception if the queue is emptyThis exception is specified in the queue ADT

Algorithm dequeue()if isEmpty() then

throw EmptyQueueException else

o Q[f]f (f + 1) mod Nreturn o

Q0 1 2 rf

Q0 1 2 fr

Trees 14Dr.Alagoz

Queue Interface in Java

Java interface corresponding to our Queue ADTRequires the definition of class EmptyQueueExceptionNo corresponding built-in Java class

public interface Queue {

public int size();

public boolean isEmpty();

public Object front()throws EmptyQueueException;

public void enqueue(Object o);

public Object dequeue() throws EmptyQueueException;

}

Trees 15Dr.Alagoz

Application: Round Robin Schedulers

We can implement a round robin scheduler using a queue, Q, by repeatedly performing the following steps:

1. e = Q.dequeue()2. Service element e3. Q.enqueue(e)

The Queue

Shared Service

1. Deque the next element

3. Enqueue the serviced element

2 . Service the next element

Trees 16

Trees (Background)

Make Money Fast!

StockFraud

KG programming

BankRobbery

Trees 17Dr.Alagoz

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 charts File systems Programming

environments

subtree

Computers”R”Us

Sales R&DManufacturing

Laptops DesktopsUS International

Europe Asia Canada

Trees 18Dr.Alagoz 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

Trees 19Dr.Alagoz

Tree Abstract Data Types We use positions to abstract nodesGeneric methods:

integer size() boolean isEmpty() Iterator elements() Iterator positions()

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

children(p)

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

Update method: object replace (p, o)

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

Trees 20Dr.Alagoz

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 KG programming

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)

Trees 21Dr.Alagoz

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)

Data Structure Course

Homeworks LecturesProject

programs

Name1.java Name2.javaHw1 Hw k Name3.java

9

3

1

7

2 4 5 6

8

Trees 22Dr.Alagoz

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 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

Trees 23Dr.Alagoz

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 childAlternative 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

Trees 24Dr.Alagoz

Arithmetic Expression TreeBinary 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

Trees 25Dr.Alagoz

Decision TreeBinary 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?

Durumcu Emmi

DurumcuBaba

Xburger Café De Paragon

Yes No

Yes No Yes No

Trees 26Dr.Alagoz

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

Trees 27Dr.Alagoz

BinaryTree ADT

The BinaryTree ADT extends the Tree ADT, i.e., it inherits all the methods of the Tree ADTAdditional 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

Trees 28Dr.Alagoz

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))

Trees 29Dr.Alagoz

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 2The result is: ???

Trees 30Dr.Alagoz

Euler Tour Traversal (*)Generic 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

R

Trees 31Dr.Alagoz

Template Method Pattern (*)

Generic 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 children

A Result object with fields leftResult, rightResult and finalResult 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.left(p));visitBelow(p, r);r.rightResult = eulerTour(tree.right(p));visitRight(p, r);return r.finalResult;

} …

Trees 32Dr.Alagoz

Specializations of EulerTour(*)

We show how to specialize class EulerTour to evaluate an arithmetic expressionAssumptions

External nodes store Integer objects

Internal 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);

}

}

Trees 33Dr.Alagoz

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

Trees 34Dr.Alagoz

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

Trees 35Dr.Alagoz

Array-Based Representation of Binary Trees

nodes are stored in an array

let rank(node) be defined as follows: 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

Trees 36Dr.Alagoz

Solved Problems & HWLA1. A) Describe the output of the following series of stack operations on a single,

initially empty stack: push(5), push(3), pop(), push(2), push(8), pop(), pop(), push(9), push(1), pop(), push(7), push(6), pop(), pop(), push(4), pop(), pop().55 355 25 2 85 255 95 9 15 95 9 75 9 7 65 9 75 95 9 45 95

Trees 37Dr.Alagoz

Solved Problems & HWLA1.B) Describe the output of the following series of queue operations on a single,

initially empty queue: enqueue(5), enqueue(3), dequeue(), enqueue(2), enqueue(8), dequeue(), dequeue(), enqueue(9), enqueue(1), dequeue(), enqueue(7), enqueue(6), dequeue(), dequeue(), enqueue(4), dequeue(), dequeue(). Solution The head of the queue is on the left.55 333 23 2 82 888 98 9 19 19 1 79 1 7 61 7 67 67 6 46 4

Trees 38Dr.Alagoz

Solved Problems & HWLA1.C) Describe in pseudo-code a linear-time algorithm for reversing a queue Q. To

access the queue, you are only allowed to use the methods of queue ADT. Hint : Considerusing an auxiliary data structure.Solution We empty queue Q into an initially empty stack S, and then empty S back into Q.Algorithm ReverseQueue(Q)Input: queue QOutput: queue Q in reverse orderS is an empty stackwhile (! Q.isEmpty()) do S.push(Q.dequeue())while (! S.isEmpty()) do Q.enqueue(S.pop())

Write a java program for a), b) and c) the above stack operation. Assume initially empty stack. Maximum stack size is 5 elements. The program should give ‘the stack is full’ , and “the stack is empty” messages when more than 5 consecutive push() and pop () is made, respectively. Make other assumptions if needed..

Trees 39Dr.Alagoz

Solved Problems & HWLA

Solve Exercises in Chapter 4 : 2, 4, 6, 8, 9, 19, 44, 48,51

4.1) (a) A . (b) G, H, I , L , M, and K . 4.3) 4

4.5) Proof is by induction. The theorem is trivially true for h = 0. Assume true for h = 1, 2, ..., k . A tree of height k +1 can have two subtrees of height at most k . These can have at most 2^ (k +1) - 1 nodes each by the induction hypothesis. These 2^ (k +2) -2 nodes plus the root prove the theorem for height k +1 and hence for all heights.

4.7) This can be shown by induction. In a tree with no nodes, the sum is zero, and in a one-node tree, the root is a leaf at depth zero, so the claim is true.

Assume that the theorem is true for all trees with at most k nodes. Consider any tree with k +1 nodes. Such a tree consists of an i node left subtree

and a k - i node right subtree. By the inductive hypothesis, the sum for the left subtree leaves is at most one wrto the left tree root. Because all leaves are one deeper with respect to the original tree than wrto the subtree, the sum is at most 1/ 2 wrto the root. Similar logic implies that the sum for leaves in the right subtree is at most 1/ 2 , proving the theorem.

The equality is true if and only if there are no nodes with one child. If there is a node with one child, the equality cannot be true because adding the second child would increase the sum to higher than 1. If no nodes have one child, then we can find and remove two sibling leaves, creating a new tree. It is easy to see that this new tree has the same sum as the old. Applying this step repeatedly, we arrive at a single node, whose sum is 1. Thus the original tree had sum 1.

Trees 40Dr.Alagoz

Take Home Quiz

Write a short paper on one of the followings: Binary search tree, AVL-tree, Splay tree and B-tree. (Word document, 12 times new roman, at most 2 pages)

Name your document as Lastname.Name-cmpe250.doc Email your document to TA anytime before October 30, 2007 (Sharp). Subject: Cmpe250 HW1

Write a short paper on one of the followings: Binary search tree, AVL-tree, Splay tree and B-tree. (Word document, 12 times new roman, at most 2 pages)

Name your document as Lastname.Name-swe510.doc Email your document to me anytime before October 30, 2007 (Sharp). Subject: swe510 HW1