Lecture 9 CS2013.

Slides:



Advertisements
Similar presentations
Trees and Binary Trees Become Rich Force Others to be Poor Rob Banks
Advertisements

Trees1 More on Trees University Fac. of Sci. & Eng. Bus. School Law School CS Dept. EE Dept. Math. Dept.
Data Structures Lecture 6 Fang Yu Department of Management Information Systems National Chengchi University Fall 2010.
Trees Briana B. Morrison Adapted from Alan Eugenio.
1 prepared from lecture material © 2004 Goodrich & Tamassia COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material.
© 2004 Goodrich, Tamassia Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery.
© 2004 Goodrich, Tamassia Priority Queues1 Heaps: Tree-based Implementation of a Priority Queue.
© 2004 Goodrich, Tamassia Trees1 Chapter 7 Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery.
Trees1 Recursion Recursion is a concept of defining a method that makes a call to itself.
Chapter 7: Trees Objectives:
© 2004 Goodrich, Tamassia Trees1 Lecture 04 Trees Topics Trees Binary Trees Binary Search trees.
Elementary Data Structures Stacks, Queues, & Lists Amortized analysis Trees.
1 Chapter 7 Trees. 2 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.
© 2004 Goodrich, Tamassia Trees1 this is a tree. © 2004 Goodrich, Tamassia Trees2 What is a Tree? In computer science, a tree is an abstract model of.
Trees COMP53 Oct 31, What is a Tree? A tree is an abstract model of a hierarchical structure A tree consists of nodes with a parent-child relation.
Trees1 Part-C Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery.
General Trees. Tree Traversal Algorithms. Binary Trees. 2 CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 © 2010 Goodrich, Tamassia.
Trees Chapter 8.
Trees.
Make Money Fast! Stock Fraud Apply shortcuts Bank Robbery Just For Laughs Trees This one is cool eITnotes.com For more notes and topics visit:
Trees CSCI 3333 Data Structures. Acknowledgement  Dr. Bun Yue  Mr. Charles Moen  Dr. Wei Ding  Ms. Krishani Abeysekera  Dr. Michael Goodrich  Dr.
Chapter 7:Trees Nancy Amato Parasol Lab, Dept. CSE, Texas A&M University Acknowledgement: These slides are adapted from slides provided with Data Structures.
Saturday, 04 Apr 2010 University of Palestine Computer Science II Trees.
Trees. 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.
Trees 4/23/2017 Trees.
© 2004 Goodrich, Tamassia Trees1 Text Book: M. T. Goodrich and R. Tamassia, "Data Structures and Algorithms in Java," 4th edition, 2006, Wiley & Sons,
Trees by Dr. Bun Yue Professor of Computer Science CSCI 3333 Data Structures.
Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery © 2010 Goodrich, Tamassia.
Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery © 2010 Goodrich, Tamassia.
Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery © 2013 Goodrich, Tamassia, Goldwasser.
Trees trees binary trees traversals of trees template method pattern
CH 7. TREES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY.
24 January Trees CSE 2011 Winter Trees Linear access time of linked lists is prohibitive  Does there exist any simple data structure for.
CH 7 : TREE ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY.
Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery © 2010 Goodrich, Tamassia.
© 2004 Goodrich, Tamassia Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery.
TREE Ahsan Ahmed College of Computer and Information Science Majma’ah University 1.
1 COMP9024: Data Structures and Algorithms Week Five: Trees Hui Wu Session 1, 2015
What is a Tree? Formally, we define a tree T as a set of nodes storing elements such that the nodes have a parent-child relationship, that satisfies the.
Elementary Data Structures
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery
Trees 5/2/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
Trees 5/10/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
Searching (and into Trees)
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery Trees
University of Palestine
Trees 8/7/2018 2:27 PM Binary Trees © 2010 Goodrich, Tamassia Trees.
Trees 二○一八年八月二十六日 Part-C Trees Trees.
Trees Chuan-Ming Liu Computer Science & Information Engineering
© 2013 Goodrich, Tamassia, Goldwasser
Trees 9/21/2018 9:58 PM Trees this is a tree Trees.
COSC2100: Data Structures and Algorithms
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery
Elementary Data Structures
Week nine-ten: Trees Trees.
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery Trees
Trees "A tree may grow a thousand feet tall, but its leaves will return to its roots." -Chinese Proverb CLRS, Section 10.4.
Lecture 12 CS203 1.
Trees Palestine Gaza West Bank 48 Stolen Land Trees Trees
Lecture 8: Iterators, Trees
Copyright © Aiman Hanna All rights reserved
CS210- Lecture 9 June 20, 2005 Announcements
1 Lecture 10 CS2013.
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery
CS203 Lecture 14.
Trees.
NATURE VIEW OF A TREE leaves branches root. NATURE VIEW OF A TREE leaves branches root.
Presentation transcript:

Lecture 9 CS2013

Iterators An iterator is a software design pattern that abstracts the process of scanning through a sequence of elements, one element at a time. © 2014 Goodrich, Tamassia, Goldwasser Lists and Iterators 2

The Iterable Interface Java defines a parameterized interface, named Iterable, that includes the following single method: iterator( ): Returns an iterator of the elements in the collection. An instance of a typical collection class in Java, such as an ArrayList, is iterable (but not itself an iterator); it produces an iterator for its collection as the return value of the iterator( ) method. Each call to iterator( ) returns a new iterator instance, thereby allowing multiple (even simultaneous) traversals of a collection. © 2014 Goodrich, Tamassia, Goldwasser Lists and Iterators 3

The for-each Loop Java’s Iterable class also plays a fundamental role in support of the “for-each” loop syntax: is equivalent to: © 2014 Goodrich, Tamassia, Goldwasser Lists and Iterators 4

Comparable The Comparable interface makes it easy to sort objects in programmer-defined sort orders. Here is an example of the interface declaration: public class Student implements Comparable<Student> Note the parameterization of Comparable, which looks just like the parameterization used when declaring a list. For now, use the class name of the current class as the parameter.

Comparable Comparables (types which implement Comparable) must contain compareTo() methods. compareTo() is an instance method that compares the current object with another one sent as a parameter. compareTo() can compare two objects (the instance on which it is called and the one passed in as a parameter) using any method you can code. It should return: 0 if the two objects are equal in the desired sort order a negative number, usually -1,if the instance object should be earlier in the sort order than the parameter object a positive number, usually 1, if the parameter object should be earlier in the sort order than the instance object

CompareTo } package students; public class Student implements Comparable<Student>{ private String name; private double gpa; public Student(String nameIn, Double gpaIn){ name = nameIn; gpa = gpaIn; } public String toString(){ return "Name: " + name + "; GPA: " + gpa; @Override public int compareTo(Student otherStudent) { return (this.gpa < otherStudent.gpa? -1:1);

CompareTo package students; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class GradeBook { public static void main(String[] args) { List<Student> students = new ArrayList<Student>(); String[] names = {"Skipper", "Gilligan", "Mary Anne", "Ginger", "Mr. Howell", "Mrs. Howell", "The Professor"}; double[] gpas = {2.7, 2.1, 3.9, 3.5, 3.4, 3.2, 4.0}; Student currStudent; for(int counter = 0; counter < names.length; counter++){ currStudent=new Student(names[counter], gpas[counter]); students.add(currStudent); } // output the data System.out.println("Unsorted:"); for(Student s: students) System.out.println(s); Collections.sort(students); System.out.println("\nSorted:"); System.out.println("Result of calling compareTo on " + students.get(0) + " with " + students.get(3) + " as parameter: " + students.get(0).compareTo(students.get(3))); System.out.println("Result of calling compareTo on " + students.get(6) + " with " + students.get(2) + " as parameter: " + students.get(6).compareTo(students.get(2)));

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 © 2014 Goodrich, Tamassia, Goldwasser Trees 9

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 © 2014 Goodrich, Tamassia, Goldwasser Trees 10

Tree ADT We use positions to abstract nodes Generic methods: integer size() boolean isEmpty() Iterator iterator() Iterable positions() Accessor methods: position root() position parent(p) Iterable children(p) Integer numChildren(p) Query methods: boolean isInternal(p) boolean isExternal(p) boolean isRoot(p) Additional update methods may be defined by data structures implementing the Tree ADT © 2014 Goodrich, Tamassia, Goldwasser Trees 11

Java Interface Methods for a Tree interface: © 2014 Goodrich, Tamassia, Goldwasser Trees 12

Binary Trees A list, stack, or queue is a linear structure that consists of a sequence of elements. A binary tree, on the other hand, is a hierarchical structure. It is either empty or consists of an element, called the root, and at most two distinct binary trees, called the left subtree and right subtree. 13

Binary Trees Applications: 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 D E F G H I © 2014 Goodrich, Tamassia, Goldwasser Trees 14

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) position sibling(p) The above methods return null when there is no left, right, or sibling of p, respectively Update methods may be defined by data structures implementing the BinaryTree ADT © 2014 Goodrich, Tamassia, Goldwasser Trees 15

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 © 2014 Goodrich, Tamassia, Goldwasser Trees 16

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 © 2014 Goodrich, Tamassia, Goldwasser Trees 17

Nodes are stored in an array A Array-Based Representation of Binary Trees Nodes are stored in an array A A A B D … G H … 1 2 1 2 9 10 B D Node v is stored at A[rank(v)] rank(root) = 0 if node is the left child of parent(node), rank(node) = 2  rank(parent(node)) + 1 if node is the right child of parent(node), rank(node) = 2  rank(parent(node)) + 2 3 4 5 6 E F C J 9 10 G H © 2014 Goodrich, Tamassia, Goldwasser Trees 18

Tree Traversal Tree traversal is the process of visiting each node in the tree exactly once. There are several ways to traverse a tree. This section presents inorder, preorder, postorder, depth-first, and breadth-first traversals. Inorder traversal visits the left subtree of the current node first recursively, then the current node itself, and finally the right subtree of the current node recursively.   Postorder traversal visits the left subtree of the current node first, then the right subtree of the current node, and finally the current node itself. Preorder traversal visits the current node first, then the left subtree of the current node recursively, and finally the right subtree of the current node recursively. Breadth-first traversal visits the nodes level by level. First visit the root, then all children of the root from left to right, then grandchildren of the root from left to right, and so on. 19

Tree Traversal Algorithm preOrder(v) Algorithm postOrder(v) visit(v) for each child w of v preorder (w) Algorithm postOrder(v) for each child w of v postOrder (w) visit(v) Algorithm inOrder(v) if left (v) ≠ null inOrder (left (v)) visit(v) if right(v) ≠ null inOrder (right (v)) 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 Ponzi Scheme 2.3 Bank Robbery 1.1 Greed 1.2 Avidity © 2014 Goodrich, Tamassia, Goldwasser 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 cs16/ 8 3 7 todo.txt 1K homeworks/ programs/ 1 2 4 5 6 h1c.doc 3K h1nc.doc 2K DDR.java 10K Stocks.java 25K Robot.java 20K © 2014 Goodrich, Tamassia, Goldwasser Trees 22

Inorder Traversal Algorithm inOrder(v) if left (v) ≠ null 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 left (v) ≠ null inOrder (left (v)) visit(v) if right(v) ≠ null inOrder (right (v)) 6 2 8 1 4 7 9 3 5 © 2014 Goodrich, Tamassia, Goldwasser Trees 23

Print Arithmetic Expressions Algorithm printExpression(v) if left (v) ≠ null print(“(’’) inOrder (left(v)) print(v.element ()) if right(v) ≠ null 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)) © 2014 Goodrich, Tamassia, Goldwasser Trees 24

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(left(v)) y  evalExpr(right(v))   operator stored at v return x  y +  - 2 5 1 3 © 2014 Goodrich, Tamassia, Goldwasser Trees 25

Tree Traversal, cont. Breadth-first traversal visits the nodes level by level. First visit the root, then all children of the root from left to right, then grandchildren of the root from left to right, and so on. For example, in the tree below inorder is 45 55 57 59 60 67 100 101 107 postorder is 45 59 57 55 67 101 107 100 60. preorder is 60 55 45 57 59 100 67 107 101. breadth-first traversal is 60 55 100 45 57 67 107 59 101. 26

Breadth First Traversal Breadth First Search is not a wise way to find a particular element in a binary search tree, since it does not take advantage of the (log n) binary search we can get in a well-balanced tree. However, the term is often used loosely to describe breadth-first traversal of an entire data structure. The most likely actual use case for BFS with a BST is to test whether your trees are being constructed correctly. A future lab will include a method to do a BFS of a data structure you will create yourself. Here is the algorithm: Create a permanent queue to hold all elements. Create another, temporary queue to hold elements that you are processing to find the BFS order. Add the root to the temporary queue. As long as there are node references in the temporary queue, poll them one at a time, add them to the permanent queue, and add any left or right references to the temporary queue When the last node is polled from the temporary queue, the permanent list is complete. 27

28 PriorityQueue A PriorityQueue removes items in sorted order from lowest to highest value, following a convention that the most important item gets the lowest value, as in "First in Command, Second in Command," etc. Change the Queue in the swingset example from an earlier lecture to a PriorityQueue; the children will take turns in alphabetical order To control the priority order, use a PriorityQueue with objects of a class in which compareTo() is implemented to sort in the order you need, or use a Comparator (coming up in this lecture)