CSE 143 Lecture 17 Binary Search Trees and Comparable slides created by Ethan Apter

Slides:



Advertisements
Similar presentations
Chapter 7. Binary Search Trees
Advertisements

Singly linked lists Doubly linked lists
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Binary Trees. DCS – SWC 2 Binary Trees Sets and Maps in Java are also available in tree-based implementations A Tree is – in this context – a data structure.
CSE 143 Lecture 18 Binary Trees read slides created by Marty Stepp and Hélène Martin
CS 206 Introduction to Computer Science II 02 / 20 / 2009 Instructor: Michael Eckmann.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
CS 206 Introduction to Computer Science II 10 / 01 / 2008 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 10 / 14 / 2009 Instructor: Michael Eckmann.
CSE 143 Lecture 19 Binary Search Trees read 17.3 slides created by Marty Stepp
Building Java Programs Binary Search Trees reading: 17.3 – 17.4.
Properties: -Each node has a value -The left subtree contains only values less than the parent node’s value -The right subtree contains only values greater.
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
CS 46B: Introduction to Data Structures July 30 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
Data Structures - CSCI 102 Binary Tree In binary trees, each Node can point to two other Nodes and looks something like this: template class BTNode { public:
Thought for the Day “To become truly great, one has to stand with people, not above them.” – Charles de Montesquieu.
Building Java Programs Chapter 17 Binary Trees. 2 Creative use of arrays/links Some data structures (such as hash tables and binary trees) are built around.
Building Java Programs Binary Search Trees; TreeSet.
CSE 143 Lecture 20 Binary Search Trees continued; Tree Sets read slides created by Marty Stepp and Hélène Martin
AITI Lecture 20 Trees, Binary Search Trees Adapted from MIT Course 1.00 Spring 2003 Lecture 28 and Tutorial Note 10 (Teachers: Please do not erase the.
Binary Search Trees Binary Search Trees (BST)  the tree from the previous slide is a special kind of binary tree called a binary.
Topic 15 The Binary Search Tree ADT Binary Search Tree A binary search tree (BST) is a binary tree with an ordering property of its elements, such.
Binary Search Trees Nilanjan Banerjee. 2 Goal of today’s lecture Learn about Binary Search Trees Discuss the first midterm.
CS 206 Introduction to Computer Science II 10 / 05 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 02 / 13 / 2009 Instructor: Michael Eckmann.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
CSE 143 Lecture 22 Binary Search Trees continued; Tree Sets read slides adapted from Marty Stepp and Hélène Martin
CSE 143 Lecture 21 Binary Search Trees, continued read slides created by Marty Stepp
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
CSE 143 Lecture 13 Recursive Backtracking slides created by Ethan Apter
CSE 143 Lecture 20 Binary Search Trees read 17.3 slides created by Marty Stepp
(c) University of Washington20c-1 CSC 143 Binary Search Trees.
CSE 143 Lecture 20 Binary Search Trees continued; Tree Sets
CSE 373 Binary search trees; tree height and balance
Trees.
Building Java Programs
Building Java Programs Chapter 17
slides created by Marty Stepp and Alyssa Harding
Building Java Programs
slides created by Alyssa Harding
Writing Methods AP Computer Science A.
slides created by Ethan Apter
Binary Trees Based on slides by Alyssa Harding & Marty Stepp
CSE 143 Lecture 20 Binary Search Trees, continued read 17.3
slides created by Ethan Apter
Lecture 12 CS203 1.
Building Java Programs
Building Java Programs
slides created by Ethan Apter
Binary Search Trees continued; Tree Sets
Lecture 21: Binary Search Trees; TreeSet
slides created by Alyssa Harding
CSE 143 Lecture 25 Set ADT implementation; hashing read 11.2
Building Java Programs
Building Java Programs
CSE 143 Lecture 2 ArrayIntList, binary search
Lecture 21: Binary Search Trees; TreeSet
slides created by Ethan Apter
Binary Search Trees reading: 17.3 – 17.4
Hashing based on slides by Marty Stepp
Trees.
slides created by Ethan Apter and Marty Stepp
Linked Lists and Loops based on slides by Ethan Apter
Binary Search Trees Based on slides by Marty Stepp & Alyssa Harding
slides created by Ethan Apter
Presentation transcript:

CSE 143 Lecture 17 Binary Search Trees and Comparable slides created by Ethan Apter

2 Binary Search Tree (BST) Binary search tree: a binary tree on which you can perform binary search For every subtree in a binary search tree, the following property holds: Remember: this property holds for every subtree, not just for the overall root x values <= xvalues > x This is sometimes called the “binary search tree property”

3 Duplicate Values We must handle duplicates somehow We’re going to handle duplicates by putting them in the left subtree (as shown on the previous slide) But there are also other options: –we could choose to not allow duplicates in our tree –we could choose to put the duplicates in the right subtree It doesn’t really matter which one we choose, so long as we’re consistent

4 BST of Names Let’s create a BST of names (Strings) How will we compare one name to another? One name is less than another when the former comes before the latter alphabetically –so “A” < “B” One name is greater than another when the former comes after the latter alphabetically –so “B” > “A”

5 BST of Names Let’s start with an empty tree and add the following names in the given order: –Peter, Michael, Kim, Morgan, Baron, and Toby Peter

6 BST of Names Let’s start with an empty tree and add the following names in the given order: –Peter, Michael, Kim, Morgan, Baron, and Toby Peter Michael

7 BST of Names Let’s start with an empty tree and add the following names in the given order: –Peter, Michael, Kim, Morgan, Baron, and Toby Peter Michael Kim

8 BST of Names Let’s start with an empty tree and add the following names in the given order: –Peter, Michael, Kim, Morgan, Baron, and Toby Peter Michael KimMorgan

9 BST of Names Let’s start with an empty tree and add the following names in the given order: –Peter, Michael, Kim, Morgan, Baron, and Toby Peter Michael KimMorgan Baron

10 BST of Names Let’s start with an empty tree and add the following names in the given order: –Peter, Michael, Kim, Morgan, Baron, and Toby Peter Michael KimMorgan Baron Toby

11 BST of Names What’s the in-order traversal of this tree? –Baron, Kim, Michael, Morgan, Peter, Toby –notice that this is also sorted order! Why does this happen? in-order traversal –left subtree, current node, right subtree in-order traversal in a BST –values current value left subtreeright subtreecurrent node

12 add Let’s write an add method that will preserve the binary search tree property public void add(int value) {... } Like most recursive tree methods, we’ll need a private helper method to keep track of our current node We also know to use “x = change(x)” because we’re modifying the tree

13 add Here’s our updated add method public void add(int value) { overallRoot = add(overallRoot, value); } private IntTreeNode add(IntTreeNode root, int value) {... } Now we have to write the rest of the code

14 add What’s the simplest tree we could add a node to? –the empty tree –this is our base case For the empty tree, we’ll just return a new node What about our recursive case(s)? –if the value to add is less than or equal to the value of the current node...add a new node to the left subtree –if the value to add is greater than the value of the current node...add a new node to the right subtree

15 add Here’s our completed add method public void add(int value) { overallRoot = add(overallRoot, value); } private IntTreeNode add(IntTreeNode root, int value) { if (root == null) root = new IntTreeNode(value); else if (value <= root.data) root.left = add(root.left, value); else root.right = add(root.right, value); return root; }

16 BST Wrap-up We’ve seen that BSTs can handle different kinds of objects –String s are sorted alphabetically –int s are sorted by non-decreasing value String s can be compared to other String s int s can be compared to other int s So we could even define our own class to put in a BST, so long as we can compare different instances of this class –you’ll have to write a class like this on your final

17 PerceivedTemperature Let’s write a simple class called PerceivedTemperature that keeps track of both the perceived temperature and actual temperature. Constructor code public class PerceivedTemperature { private int pTemp; private int aTemp; public class PerceivedTemperature(int pt, int at) { pTemp = pt; aTemp = at; }

18 PerceivedTemperature Let’s also give it a few more simple methods public int getPerceivedTemperature() { return pTemp; } public int getActualTemperature() { return aTemp; } public String toString() { return pTemp + “ (“ + aTemp + “) “ + degrees; } It’s still a simple class, but now it has some functionality

19 Some Client Code Let’s also make some simple client code import java.util.*; public class PerceivedTemperatureMain { public static void main(String[] args) { List temps = new ArrayList (); temps.add(new PerceivedTemperature(104, 103)); temps.add(new PerceivedTemperature(104, 101)); temps.add(new PerceivedTemperature(88, 90)); System.out.println(temps); } Which produces the following output: [104 (103) degrees, 104 (101) degrees, 88 (90) degrees]

20 Some Client Code But what if we wanted to sort our list before printing? There’s a static method in the Java library called Collections.sort that takes a list as a parameter But if we add the following line to our client code: Collections.sort(temps); We get a compiler error –we haven’t told Java how to sort PerceivedTemperature s!

21 Comparable If we want our class to be compatible with tools like Arrays.sort and Collections.sort, we need to tell Java how our class is ordered Java provides the Comparable interface: public interface Comparable { public int compareTo(T other); } compareTo is not a method in Object because some things aren’t comparable –when is one Scanner greater than another Scanner ? –when is one Map less than another Map ?

22 compareTo What does compareTo return? Java’s convention is: –if compareTo returns a negative number, it means “less” –if compareTo returns a zero, it means “equal” –if compareTo returns a positive number, it means “greater” Some examples: –if x.compareTo(y) returns -7, then x < y –if x.compareTo(y) returns 0, then x == y –if x.compareTo(y) returns 37, then x > y

23 compareTo For the PerceivedTemperature class, the single most important piece of data is the perceived temperature We’ll use this to write an attempt of compareTo : public int compareTo(PerceivedTemperature other) { return pTemp - other.pTemp; } Notice that the above version works correctly –e.g. if pTemp < other.pTemp, it returns a negative number But what if the perceived temperatures are equal? –in this case, let’s break ties by the actual temperatures

24 compareTo Final version of compareTo : public int compareTo(PerceivedTemperature other) { if (pTemp == other.pTemp) return aTemp - other.aTemp; else return pTemp - other.pTemp; } Now if we try to compile our client code......we still get a compiler error! But why? We wrote a correct compareTo ! –we forgot to implement the Comparable interface

25 Implementing Comparable We need to have PerceivedTemperature implement the Comparable interface: public class PerceivedTemperature implements Comparable {... } Remember: by implementing the interface we’re promising Java that we’ve written a compareTo method. Only after we make this promise will Java let us use Collections.sort Notice we have to say what it is comparable to (namely, other PerceivedTemperature objects)

26 Updated Client Code Here’s our updated our client code: import java.util.*; public class PerceivedTemperatureMain { public static void main(String[] args) { List temps = new ArrayList (); temps.add(new PerceivedTemperature(104, 103)); temps.add(new PerceivedTemperature(104, 101)); temps.add(new PerceivedTemperature(88, 90)); Collections.sort(temps); System.out.println(temps); } Which now produces the following output: [88 (90) degrees, 104 (101) degrees, 104 (103) degrees]

27 compareTo and double s Suppose PerceivedTemperature had stored its temperatures as double s instead of as int s. How would this affect compareTo ? –compareTo is supposed to return an int, but now our subtraction operations return double s An attempt at fixing compareTo by casting to int s public int compareTo(PerceivedTemperature other) { if (pTemp == other.pTemp) return (int)(aTemp - other.aTemp); else return (int)(pTemp - other.pTemp); } This doesn’t always work!

28 compareTo and double s Simple casting will return the wrong answer if the difference between the two temperatures is both non-zero and less than one –any difference strictly between -1.0 and 1.0 is converted to 0 We need to check if the difference between the temperatures is non-zero The easiest way to do this is with > and < –e.g. if (pTemp > other.pTemp)

29 compareTo and double s One solution (assuming temperatures are doubles): public int compareTo(PerceivedTemperature other) { if (pTemp == other.pTemp) return compareDoubles(aTemp, other.aTemp); else return compareDoubles(pTemp, other.pTemp); } private int compareDoubles(double d1, double d2) { if (d1 < d2) return -1; else if (d1 > d2) return 1; else return 0; }