Presentation is loading. Please wait.

Presentation is loading. Please wait.

Stacks (Background) Trees.

Similar presentations


Presentation on theme: "Stacks (Background) Trees."— 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 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 Trees

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

5 Stack Interface in Java
public interface Stack { public int size(); public boolean isEmpty(); public Object top() throws EmptyStackException; public void push(Object o); public Object pop() throws EmptyStackException; } 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 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 Trees

7 Trees 8/2/2018 3:47 PM Queues (Background) Trees

8 The Queue ADT Auxiliary queue operations: Exceptions
Trees 8/2/2018 3:47 PM 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 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 wrapped-around configuration
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 normal configuration Q 1 2 r f wrapped-around configuration Q 1 2 f r Trees

11 Queue Operations We use the modulo operator (remainder of division)
Algorithm size() return (N - f + r) mod N Algorithm isEmpty() return (f = r) Q 1 2 r f Q 1 2 f r Trees

12 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 1 2 r f Q 1 2 f r Trees

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

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

15 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) The Queue Shared Service 1 . Deque the next element 3 Enqueue the serviced element 2 Service the Trees

16 Trees (Background) Make Money Fast! Stock Fraud KG programming
8/2/2018 3:47 PM Trees (Background) Make Money Fast! Stock Fraud KG programming Bank Robbery Trees

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

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

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

20 Preorder Traversal Algorithm preOrder(v) visit(v)
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 Algorithm preOrder(v) visit(v) for each child w of v preorder (w) 1 Make Money Fast! 2 5 9 1. Motivations 2. Methods References 6 7 8 3 4 2.1 Stock Fraud 2.2 KG programming 2.3 Bank Robbery 1.1 Greed 1.2 Avidity Trees

21 Postorder Traversal Algorithm postOrder(v) for each child w of v
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) 9 Data Structure Course 8 3 7 Project programs Homeworks Lectures 1 2 4 5 6 Hw1 Hw k Name1.java Name2.java Name3.java Trees

22 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 B C D E F G H I Trees

23 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 a 1 3 b Trees

24 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 Durumcu Baba Xburg Café De Paragon Durumcu Emmi Trees

25 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  2h h  log2 e h  log2 (n + 1) - 1 Trees

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

27 Inorder Traversal Algorithm inOrder(v) if hasLeft (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 Algorithm inOrder(v) if hasLeft (v) inOrder (left (v)) visit(v) if hasRight (v) inOrder (right (v)) 6 2 8 1 4 7 9 3 5 Trees

28 Print Arithmetic Expressions
Algorithm printExpression(v) if hasLeft (v) print(“(’’) inOrder (left(v)) print(v.element ()) if hasRight (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 ((2  (a - 1)) + (3  b)) Trees

29 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 5 1 3 The result is: ??? Trees

30 Euler Tour Traversal +   2 - 3 2 5 1
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 Array-Based Representation of Binary Trees
nodes are stored in an array 1 A H G F E D C B J 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

32 Solved Problems & HWLA Trees
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 2 5 2 8 5 9 5 9 1 5 9 7 5 9 4 Trees

33 Solved Problems & HWLA Trees
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 1 7 6 7 6 7 6 4 6 4 Trees

34 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

35 Solved Problems & HWLA 4.1) (a) A . (b) G, H, I , L , M, and K ) 4 4.5) Proof is by induction. The theorem is trivially true for h = 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

36 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; } … Trees

37 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 ); } } Trees

38 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

39 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 B A D C E C E Trees


Download ppt "Stacks (Background) Trees."

Similar presentations


Ads by Google