Lecture 8: Iterators, Trees

Slides:



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

Data Structures Lecture 6 Fang Yu Department of Management Information Systems National Chengchi University Fall 2010.
Trees Briana B. Morrison Adapted from Alan Eugenio.
© 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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 26 Binary Search Trees.
Chapter 7: Trees Objectives:
© 2004 Goodrich, Tamassia Trees1 Lecture 04 Trees Topics Trees Binary Trees Binary Search 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.
Trees Chapter 8.
1 Chapter 25 Trees Iterators Heaps Priority Queues.
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.
Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery © 2010 Goodrich, Tamassia.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 25 Trees, Iterators,
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.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 19 Binary Search Trees.
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)
Lecture 1 (UNIT -4) TREE SUNIL KUMAR CIT-UPES.
Chapter 25 Binary Search 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.
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
Copyright © Aiman Hanna All rights reserved
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Lecture 9 CS2013.
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 8: Iterators, Trees CS2013 Lecture 8: Iterators, Trees

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

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 Starbucks Chipotle Gracie’s Café Paragon © 2014 Goodrich, Tamassia, Goldwasser Trees 15

Representing Binary Trees A binary tree can be represented using a set of linked nodes. Each node contains a value and two links named left and right that reference the left child and right child, respectively, as shown in Figure 27.2. class TreeNode<E> { E element; TreeNode<E> left; TreeNode<E> right;   public TreeNode(E o) { element = o; } 16

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

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

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

The Tree Interface The Tree interface defines common operations for trees, and the AbstractTree class partially implements Tree. 20

Tree After Insertions Inorder: Adam, Daniel George, Jones, Michael, Peter, Tom Postorder: Daniel Adam, Jones, Peter, Tom, Michael, George Preorder: George, Adam, Daniel, Michael, Jones, Tom, Peter 21

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

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 23

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 24

Array-Based Representation of Binary Trees Alternative to implementation using links 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 25