CSE 143 Lecture 20. Binary Search Trees. read slides created by Marty Stepp

Similar documents
A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Algorithms and Data Structures Written Exam Proposed SOLUTION

Binary Search Trees (BST)

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Full and Complete Binary Trees

Ordered Lists and Binary Trees

Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006. Final Examination. January 24 th, 2006

Analysis of Algorithms I: Optimal Binary Search Trees

Binary Search Trees. Ric Glassey

Binary Trees and Huffman Encoding Binary Search Trees

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

Binary Heaps. CSE 373 Data Structures

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Keys and records. Binary Search Trees. Data structures for storing data. Example. Motivation. Binary Search Trees

Data Structures and Algorithms

LINKED DATA STRUCTURES

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

The ADT Binary Search Tree

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Why Use Binary Trees?

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

CompSci-61B, Data Structures Final Exam

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

J a v a Quiz (Unit 3, Test 0 Practice)

CSE 326: Data Structures B-Trees and B+ Trees

Binary Search Trees. Data in each node. Larger than the data in its left child Smaller than the data in its right child

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

From Last Time: Remove (Delete) Operation

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Topic 11 Scanner object, conditional execution

D06 PROGRAMMING with JAVA

Chapter 14 The Binary Search Tree

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Graduate Assessment Test (Sample)

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

DNS LOOKUP SYSTEM DATA STRUCTURES AND ALGORITHMS PROJECT REPORT

Binary Heap Algorithms

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Data Structures CSC212 (1) Dr Muhammad Hussain Lecture - Binary Search Tree ADT

Lecture 6: Binary Search Trees CSCI Algorithms I. Andrew Rosenberg

Binary Search Trees CMPSC 122

COMPUTER SCIENCE. Paper 1 (THEORY)

Data Structures and Algorithms Written Examination

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

ECE 122. Engineering Problem Solving with Java

PES Institute of Technology-BSC QUESTION BANK

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

1.204 Lecture 10. Greedy algorithms: Job scheduling. Greedy method

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

OPTIMAL BINARY SEARCH TREES

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Analysis of Algorithms I: Binary Search Trees

Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013

Sample CSE8A midterm Multiple Choice (circle one)

Previous Lectures. B-Trees. External storage. Two types of memory. B-trees. Main principles

Analysis of a Search Algorithm

Chapter 2 Introduction to Java programming

Building a Multi-Threaded Web Server

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Theory of Compilation

Lecture Notes on Binary Search Trees

Sample Questions Csci 1112 A. Bellaachia

Introduction to Python

AP Computer Science Java Mr. Clausen Program 9A, 9B

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

AP Computer Science File Input with Scanner

Continuous Integration Part 2

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Introduction to Java

D06 PROGRAMMING with JAVA

Alex. Adam Agnes Allen Arthur

CMSC 202H. ArrayList, Multidimensional Arrays

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

The following program is aiming to extract from a simple text file an analysis of the content such as:

Introduction to Object-Oriented Programming

Java Basics: Data Types, Variables, and Loops

Building Java Programs

D06 PROGRAMMING with JAVA

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

public static void main(string[] args) { System.out.println("hello, world"); } }

Chapter 7: Sequential Data Structures

Software Engineering Techniques

Iterators. Provides a way to access elements of an aggregate object sequentially without exposing its underlying representation.

Building Java Programs

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

10CS35: Data Structures Using C

Lecture Notes on Binary Search Trees

Transcription:

CSE 143 Lecture 20 Binary Search Trees read 17.3 slides created by Marty Stepp http://www.cs.washington.edu/143/

Binary search trees binary search tree ("BST"): a binary tree that is either: empty (null), or a root node R such that: every element of R's left subtree contains data "less than" R's data, every element of R's right subtree contains data "greater than" R's, R's left and right subtrees are also binary search trees. overall root BSTs store their elements in sorted order, which is helpful for searching/sorting tasks. 29 55 87-3 42 60 91 2

Exercise Which of the trees shown are legal binary search trees? g m q 42 5 8 11 b k x 2 7 10 18 7.2 e 4-5 1.9 9.6 18 20-1 -7 8.1 21.3 3

Searching a BST Describe an algorithm for searching the tree below for the value 31. Then search for the value 6. overall root What is the maximum number of nodes you would need to examine to perform any search? 12 18 35 4 15 22 58-2 7 13 16 19 31 40 87 4

Exercise Convert the IntTree class into a SearchTree class. The elements of the tree will constitute a legal binary search tree. Add a method contains to the SearchTree class that searches the tree for a given integer, returning true if found. If a SearchTree variable tree referred to the tree below, the following calls would have these results: tree.contains(29) true tree.contains(55) true tree.contains(63) false tree.contains(35) false 29 overall root 55 87-3 42 60 91 5

Exercise solution // Returns whether this tree contains the given integer. public boolean contains(int value) { return contains(overallroot, value); private boolean contains(inttreenode node, int value) { if (node == null) { return false; else if (node.data == value) { return true; else if (node.data > value) { return contains(node.left, value); else { // root.data < value return contains(node.right, value); 6

Adding to a BST Suppose we want to add the value 14 to the BST below. Where should the new node be added? Where would we add the value 3? 8 Where would we add 7? 5 11 If the tree is empty, where should a new value be added? 2 7 10 18 4 20 What is the general algorithm? 18 7

Adding exercise Draw what a binary search tree would look like if the following values were added to an initially empty tree in this order: 50 20 75 98 80 31 150 39 23 11 77 11 50 20 75 31 23 39 80 77 98 150 8

Exercise Add a method add to the SearchTree class that adds a given integer value to the tree. Assume that the elements of the SearchTree constitute a legal binary search tree, and add the new value in the appropriate place to maintain ordering. tree.add(49); overall root 55 29 87-3 42 60 91 49 9

An incorrect solution // Adds the given value to this BST in sorted order. public void add(int value) { add(overallroot, value); private void add(inttreenode node, int value) { if (node == null) { node = new IntTreeNode(value); else if (node.data > value) { add(node.left, value); else if (node.data < value) { add(node.right, value); // else node.data == value, so 29 // it's a duplicate (don't add) Why doesn't this solution work? -3 overallroot 42 55 60 87 91 10

The x = change(x) pattern read 17.3

A tangent: Change a point What is the state of the object referred to by p after this code? public static void main(string[] args) { Point p = new Point(3, 25); change(p); p x System.out.println(p); public static void change(point thepoint) { thepoint.x = 99; thepoint.y = -1; // answer: (99, -1) 3 y 25 12

Change point, version 2 What is the state of the object referred to by p after this code? public static void main(string[] args) { Point p = new Point(3, 25); change(p); p x System.out.println(p); public static void change(point thepoint) { thepoint = new Point(99, -1); 3 y 25 x 99 y -1 // answer: (3, 25) 13

Changing references If a method dereferences a variable (with. ) and modifies the object it refers to, that change will be seen by the caller. public static void change(point thepoint) { thepoint.x = 99; // affects p thepoint.sety(-12345); // affects p If a method reassigns a variable to refer to a new object, that change will not affect the variable passed in by the caller. public static void change(point thepoint) { thepoint = new Point(99, -1); // p unchanged thepoint = null; // p unchanged 14

Change point, version 3 What is the state of the object referred to by p after this code? public static void main(string[] args) { Point p = new Point(3, 25); change(p); p x System.out.println(p); 3 y 25 public static Point change(point thepoint) { thepoint = new Point(99, -1); return thepoint; // answer: (3, 25) x 99 y -1 15

Change point, version 4 What is the state of the object referred to by p after this code? public static void main(string[] args) { Point p = new Point(3, 25); p = change(p); p x System.out.println(p); 3 y 25 public static Point change(point thepoint) { thepoint = new Point(99, -1); return thepoint; // answer: (99, -1) x 99 y -1 16

x = change(x); If you want to write a method that can change the object that a variable refers to, you must do three things: 1. pass in the original state of the object to the method 2. return the new (possibly changed) object from the method 3. re-assign the caller's variable to store the returned result p = change(p); // in main public static Point change(point thepoint) { thepoint = new Point(99, -1); return thepoint; We call this general algorithmic pattern x = change(x); 17

x = change(x) and strings String methods that modify a string actually return a new one. If we want to modify a string variable, we must re-assign it. String s = "lil bow wow"; s.touppercase(); System.out.println(s); // lil bow wow s = s.touppercase(); System.out.println(s); // LIL BOW WOW We use x = change(x) in methods that modify a binary tree. We will pass in a node as a parameter and return a node result. The node passed in must be re-assigned via x = change(x). 18

The problem Much like with linked lists, if we just modify what a local variable refers to, it won't change the collection. node private void add(inttreenode node, int value) { if (node == null) { node = new IntTreeNode(value); 49 overallroot 55 In the linked list case, how did we actually modify the list? by changing the front by changing a node's next field -3 29 42 60 87 91 19

Applying x = change(x) Methods that modify a tree should have the following pattern: input (parameter): old state of the node output (return): new state of the node node before parameter your method return node after In order to actually change the tree, you must reassign: node = change(node, parameters); node.left = change(node.left, parameters); node.right = change(node.right, parameters); overallroot = change(overallroot, parameters); 20

A correct solution // Adds the given value to this BST in sorted order. public void add(int value) { overallroot = add(overallroot, value); private IntTreeNode add(inttreenode node, int value) { if (node == null) { node = new IntTreeNode(value); else if (node.data > value) { node.left = add(node.left, value); else if (node.data < value) { overallroot node.right = add(node.right, value); // else a duplicate return node; 29 55 87 Think about the case when node is a leaf... -3 42 60 91 21

Exercise Add a method getmin to the IntTree class that returns the minimum integer value from the tree. Assume that the elements of the IntTree constitute a legal binary search tree. Throw a NoSuchElementException if the tree is empty. int min = tree.getmin(); // -3 overall root 55 29 87-3 42 60 91 22

Exercise solution // Returns the minimum value from this BST. // Throws a NoSuchElementException if the tree is empty. public int getmin() { if (overallroot == null) { throw new NoSuchElementException(); return getmin(overallroot); private int getmin(inttreenode root) { if (root.left == null) { return root.data; else { return getmin(root.left); overallroot 55 29 87-3 42 60 91 23