1 / 40

Stacks (Background)

Stacks (Background). 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.

phuong
Download Presentation

Stacks (Background)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Stacks (Background) Trees

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

  3. 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 Abstract Data Types (ADTs) Trees

  4. 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 The Stack ADT Trees

  5. Stack Interface in Java public interfaceStack{ public int size(); public boolean isEmpty(); public Object top()throwsEmptyStackException; public voidpush(Object o); public Object pop()throwsEmptyStackException;} • Java interface corresponding to our Stack ADT • Requires the definition of class EmptyStackException • Different from the built-in Java class java.util.Stack Trees

  6. 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 Exceptions Trees

  7. Queues (Background) Trees

  8. 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 The Queue ADT Trees

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

  10. 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 0 1 2 f r Q 0 1 2 r f Array-based Queue normal configuration wrapped-around configuration Trees

  11. Q 0 1 2 f r Q 0 1 2 r f Queue Operations Algorithmsize() return(N-f +r) mod N AlgorithmisEmpty() return(f=r) • We use the modulo operator (remainder of division) Trees

  12. Q 0 1 2 f r Q 0 1 2 r f Queue Operations (cont.) Algorithmenqueue(o) ifsize()=N 1then 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 Trees

  13. Q 0 1 2 f r Q 0 1 2 r f Queue Operations (cont.) Algorithmdequeue() ifisEmpty()then throw EmptyQueueException else oQ[f] f(f + 1) mod N returno • Operation dequeue throws an exception if the queue is empty • This exception is specified in the queue ADT Trees

  14. Queue Interface in Java public interfaceQueue{ public int size(); public boolean isEmpty(); public Object front()throwsEmptyQueueException; public voidenqueue(Object o); public Object dequeue()throwsEmptyQueueException;} • Java interface corresponding to our Queue ADT • Requires the definition of class EmptyQueueException • No corresponding built-in Java class Trees

  15. The Queue 2 . Service the 3 . Enqueue the 1 . Deque the next element serviced element next element Shared Service Application: Round Robin Schedulers • We can implement a round robin scheduler using a queue, Q, by repeatedly performing the following steps: • e = Q.dequeue() • Service element e • Q.enqueue(e) Trees

  16. Trees (Background) Make Money Fast! BankRobbery StockFraud KG programming Trees

  17. Computers”R”Us Sales Manufacturing R&D US International Laptops Desktops Europe Asia Canada 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 Trees

  18. A C D B E G H F K I J Tree Terminology • Subtree: tree consisting of a node and its descendants • 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. subtree Trees

  19. Tree Abstract Data Types • 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 • 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) Trees

  20. Preorder Traversal AlgorithmpreOrder(v) visit(v) foreachchild w of v preorder (w) • 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 Make Money Fast! 2 5 9 1. Motivations 2. Methods References 6 7 8 3 4 2.3 BankRobbery 2.1 StockFraud 2.2 KG programming 1.1 Greed 1.2 Avidity Trees

  21. Postorder Traversal AlgorithmpostOrder(v) foreachchild w of v postOrder (w) visit(v) • In a postorder traversal, a node is visited after its descendants • Application: compute space used by files in a directory and its subdirectories 9 Data Structure Course 8 3 7 Project programs Homeworks Lectures 4 5 6 1 2 Name3.java Hw1 Hw k Name1.java Name2.java Trees

  22. Inorder Traversal AlgorithminOrder(v) ifhasLeft (v) inOrder (left (v)) visit(v) ifhasRight (v) inOrder (right (v)) • 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 6 2 8 1 4 7 9 3 5 Trees

  23. Binary Trees • Applications: • arithmetic expressions • decision processes • searching • 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 A C B D E F G I H Trees

  24. +   2 - 3 b a 1 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)) Trees

  25. 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 Durumcu Baba Xburger Café De Paragon Durumcu Emmi Trees

  26. Properties of Proper Binary Trees • Properties: • e = i +1 • n =2e -1 • h  i • h  (n -1)/2 • e 2h • h log2e • h log2 (n +1)-1 • Notation n number of nodes e number of external nodes i number of internal nodes h height Trees

  27. 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 BinaryTree ADT Trees

  28. +   2 - 3 b a 1 Print Arithmetic Expressions AlgorithmprintExpression(v) ifhasLeft (v)print(“(’’) inOrder (left(v)) print(v.element ()) ifhasRight (v) inOrder (right(v)) print (“)’’) • Specialization of an inorder traversal • print operand or operator when visiting node • print “(“ before traversing left subtree • print “)“ after traversing right subtree ((2  (a - 1)) + (3  b)) Trees

  29. +   2 - 3 2 5 1 Evaluate Arithmetic Expressions AlgorithmevalExpr(v) ifisExternal (v) returnv.element () else x evalExpr(leftChild (v)) y evalExpr(rightChild (v))  operator stored at v returnx  y • Specialization of a postorder traversal • recursive method returning the value of a subtree • when visiting an internal node, combine the values of the subtrees • The result is: ??? Trees

  30. 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 Trees

  31. Template Method Pattern (*) public abstract class EulerTour{ protected BinaryTree tree;protected voidvisitExternal(Position p, Result r) { }protected voidvisitLeft(Position p, Result r) { }protected voidvisitBelow(Position p, Result r) { }protected voidvisitRight(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; } … • 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 Trees

  32. Specializations of EulerTour(*) public class EvaluateExpressionextends EulerTour{ protected voidvisitExternal(Position p, Result r) {r.finalResult = (Integer) p.element(); } protected voidvisitRight(Position p, Result r) {Operator op = (Operator) p.element();r.finalResult = op.operation( (Integer) r.leftResult, (Integer) r.rightResult ); } … } • 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) Trees

  33. 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   A D F B A D F   C E C E Trees

  34. D C A B E 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 A D     C E Trees

  35. A … B D C E F J G H Array-Based Representation of Binary Trees • nodes are stored in an array 1 2 3 • 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 4 5 6 7 10 11 Trees

  36. 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 Trees

  37. 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 Trees

  38. 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.. Trees

  39. Solved Problems & HWLA • 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. • Solve Exercises in Chapter 4 : 2, 4, 6, 8, 9, 19, 44, 48,51 Trees

  40. 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-swe510.doc Email your document to me anytime before October 30, 2007 (Sharp). Subject: swe510 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-cmpe250.doc Email your document to TA anytime before October 30, 2007 (Sharp). Subject: Cmpe250 HW1 Trees

More Related