Presentation is loading. Please wait.

Presentation is loading. Please wait.

Trees1 Stacks (Background). Dr.Alagoz Trees2 Applications of Stacks Direct applications Page-visited history in a Web browser Undo sequence in a text.

Similar presentations


Presentation on theme: "Trees1 Stacks (Background). Dr.Alagoz Trees2 Applications of Stacks Direct applications Page-visited history in a Web browser Undo sequence in a text."— Presentation transcript:

1 Trees1 Stacks (Background)

2 Dr.Alagoz Trees2 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

3 Dr.Alagoz Trees3 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An 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

4 Dr.Alagoz Trees4 The Stack ADT The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in first-out scheme Think of a spring-loaded plate dispenser Main 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

5 Dr.Alagoz Trees5 Stack Interface in Java Java interface corresponding to our Stack ADT Requires the definition of class EmptyStackException Different 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; }

6 Dr.Alagoz Trees6 Exceptions Attempting the execution of an operation of ADT may sometimes cause an error condition, called an exception Exceptions 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 empty Attempting the execution of pop or top on an empty stack throws an EmptyStackException

7 Trees7 Queues (Background)

8 Dr.Alagoz Trees8 The Queue ADT The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in first-out scheme Insertions are at the rear of the queue and removals are at the front of the queue Main 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

9 Dr.Alagoz Trees9 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

10 Dr.Alagoz Trees10 Array-based Queue Use an array of size N in a circular fashion Two variables keep track of the front and rear f index of the front element r index immediately past the rear element Array location r is kept empty Q 012rf normal configuration Q 012fr wrapped-around configuration

11 Dr.Alagoz Trees11 Queue Operations We use the modulo operator (remainder of division) Algorithm size() return (N  f + r) mod N Algorithm isEmpty() return (f  r) Q 012rf Q 012fr

12 Dr.Alagoz Trees12 Queue Operations (cont.) Algorithm enqueue(o) if size() = N  1 then throw FullQueueException else Q[r]  o r  (r + 1) mod N Operation enqueue throws an exception if the array is full This exception is implementation- dependent Q 012rf Q 012fr

13 Dr.Alagoz Trees13 Queue Operations (cont.) Operation dequeue throws an exception if the queue is empty This exception is specified in the queue ADT Algorithm dequeue() if isEmpty() then throw EmptyQueueException else o  Q[f] f  (f + 1) mod N return o Q 012rf Q 012fr

14 Dr.Alagoz Trees14 Queue Interface in Java Java interface corresponding to our Queue ADT Requires the definition of class EmptyQueueException No 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; }

15 Dr.Alagoz Trees15 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 e 3. Q.enqueue(e) The Queue Shared Service 1.Deque the next element 3.Enqueue the serviced element 2.Service the next element

16 Trees16 Trees (Background) Make Money Fast! Stock Fraud KG programming Bank Robbery

17 Dr.Alagoz Trees17 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 subtree Computers”R”Us SalesR&DManufacturing LaptopsDesktops US International EuropeAsiaCanada

18 Dr.Alagoz Trees18 subtree 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 any node (3) Descendant of a node: child, grandchild, grand-grandchild, etc. A B DC GH E F IJ K Subtree: tree consisting of a node and its descendants

19 Dr.Alagoz Trees19 Tree Abstract Data Types We use positions to abstract nodes Generic 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

20 Dr.Alagoz Trees20 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. MotivationsReferences2. Methods 2.1 Stock Fraud 2.2 KG programming 1.1 Greed1.2 Avidity 2.3 Bank Robbery 1 2 3 5 4 678 9 Algorithm preOrder(v) visit(v) for each child w of v preorder (w)

21 Dr.Alagoz Trees21 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) Data Structure Course HomeworksLectures Project programs Name1.javaName2.javaHw1Hw k Name3.java 9 3 1 7 2 456 8

22 Dr.Alagoz Trees22 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 79 8 4

23 Dr.Alagoz Trees23 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 FG D E H I

24 Dr.Alagoz Trees24 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 a1 3b

25 Dr.Alagoz Trees25 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? Durumcu Emmi Durumcu Baba XburgerCafé De Paragon Yes No YesNoYesNo

26 Dr.Alagoz Trees26 Properties of Proper Binary Trees Notation n number of nodes e number of external nodes i number of internal nodes h height Properties: e  i  1 n  2e  1 h  i h  (n  1)  2 e  2 h h  log 2 e h  log 2 (n  1)  1

27 Dr.Alagoz Trees27 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

28 Dr.Alagoz Trees28 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 a1 3b ((2  ( a  1))  (3  b))

29 Dr.Alagoz Trees29 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 v return x  y    2 51 32 The result is: ???

30 Dr.Alagoz Trees30 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 51 32 L B R 

31 Dr.Alagoz Trees31 Template Method Pattern (*) Generic algorithm that can be specialized by redefining certain steps Implemented by means of an abstract Java class Visit methods that can be redefined by subclasses Template 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; } …

32 Dr.Alagoz Trees32 Specializations of EulerTour(*) We show how to specialize class EulerTour to evaluate an arithmetic expression Assumptions External nodes store Integer objects Internal nodes store Operator objects supporting method operation (Integer, Integer) public class EvaluateExpression extends 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 ); } … }

33 Dr.Alagoz Trees33  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 D A CE F B  ADF  C  E

34 Dr.Alagoz Trees34 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 D A CE   BADCE 

35 Dr.Alagoz Trees35 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 23 6 7 45 1011 A HG FE D C B J

36 Dr.Alagoz Trees36 Solved Problems & HWLA 1. 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(). 5 5 3 5 5 2 5 2 8 5 2 5 5 9 5 9 1 5 9 5 9 7 5 9 7 6 5 9 7 5 9 5 9 4 5 9 5

37 Dr.Alagoz Trees37 Solved Problems & HWLA 1.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. 5 5 3 3 3 2 3 2 8 2 8 8 8 9 8 9 1 9 1 9 1 7 9 1 7 6 1 7 6 7 6 7 6 4 6 4

38 Dr.Alagoz Trees38 Solved Problems & HWLA 1.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 : Consider using 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 Q Output: queue Q in reverse order S is an empty stack while (! 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..

39 Dr.Alagoz Trees39 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.

40 Dr.Alagoz Trees40 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


Download ppt "Trees1 Stacks (Background). Dr.Alagoz Trees2 Applications of Stacks Direct applications Page-visited history in a Web browser Undo sequence in a text."

Similar presentations


Ads by Google