Download presentation
Presentation is loading. Please wait.
1
Lecture 9 CS2013
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 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
15
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
16
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
17
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
18
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
19
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
20
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
21
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
22
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
23
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
24
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
25
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
26
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 26
27
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
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)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.