Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 8: Iterators, Trees

Similar presentations


Presentation on theme: "Lecture 8: Iterators, Trees"— Presentation transcript:

1 Lecture 8: Iterators, Trees
CS2013 Lecture 8: Iterators, Trees

2 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

3 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

4 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

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

6 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

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

8 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)));

9 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

10 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

11 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

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

13 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

14 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

15 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

16 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

17 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

18 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

19 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 postorder is preorder is breadth-first traversal is 19

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

21 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

22 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

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 23

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 24

25 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


Download ppt "Lecture 8: Iterators, Trees"

Similar presentations


Ads by Google