CMPSCI 187: Programming With Data Structures. Lecture #28: Binary Search Trees 21 November 2011

Similar documents
The Binary Search Tree ADT

CS350: Data Structures Binary Search Trees

CS 350 : Data Structures Binary Search Trees

tree nonlinear Examples

Spring 2018 Mentoring 8: March 14, Binary Trees

4/18/ Binary Search Trees (BSTs) 17.1 Adding an Element to a BST Removing an Element from a BST. 17.

a graph is a data structure made up of nodes in graph theory the links are normally called edges

Topic 14. The BinaryTree ADT

A grossly unbalanced tree, with some long paths. Next to add: When does it occur? Why is it undesirable?

Data Structures in Java

Binary Trees, Binary Search Trees

We have the pointers reference the next node in an inorder traversal; called threads

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

Motivation Computer Information Systems Storage Retrieval Updates. Binary Search Trees. OrderedStructures. Binary Search Tree

Priority Queues. 04/10/03 Lecture 22 1

Binary Search Trees. See Section 11.1 of the text.

CSI33 Data Structures

Trees. (Trees) Data Structures and Programming Spring / 28

from inheritance onwards but no GUI programming expect to see an inheritance question, recursion questions, data structure questions

ITI Introduction to Computing II

Lecture 23: Binary Search Trees

Figure 18.4 A Unix directory. 02/10/04 Lecture 9 1

ITI Introduction to Computing II

COMP 250. Lecture 22. binary search trees. Oct. 30, 2017

BINARY SEARCH TREES cs2420 Introduction to Algorithms and Data Structures Spring 2015

ITEC2620 Introduction to Data Structures

Binary Search Trees 1

CMSC 341 Lecture 10 Binary Search Trees

Outline. An Application: A Binary Search Tree. 1 Chapter 7: Trees. favicon. CSI33 Data Structures

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

Principles of Computer Science

Data Structures. Giri Narasimhan Office: ECS 254A Phone: x-3748

CSE 530A. B+ Trees. Washington University Fall 2013

Trees Chapter 19, 20. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CS 151. Binary Search Trees. Wednesday, October 10, 12

CMSC 341. Binary Search Trees CMSC 341 BST

CS102 Binary Search Trees

CmpSci 187: Programming with Data Structures Spring 2015

Some Search Structures. Balanced Search Trees. Binary Search Trees. A Binary Search Tree. Review Binary Search Trees

CSC148 Intro. to Computer Science

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

Sorted Arrays. Operation Access Search Selection Predecessor Successor Output (print) Insert Delete Extract-Min

CMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course

Uses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010

Module 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree.

Binary Trees and Huffman Encoding Binary Search Trees

Binary Search Trees. Analysis of Algorithms

void insert( Type const & ) void push_front( Type const & )

Trees, Part 1: Unbalanced Trees

CISC 235 Topic 3. General Trees, Binary Trees, Binary Search Trees

CIS 121. Binary Search Trees

Trees, Binary Trees, and Binary Search Trees

CMPSCI 187: Programming With Data Structures. Lecture #26: Binary Search Trees David Mix Barrington 9 November 2012

Self-Balancing Search Trees. Chapter 11

Readings. Priority Queue ADT. FindMin Problem. Priority Queues & Binary Heaps. List implementation of a Priority Queue

Binary Trees. BSTs. For example: Jargon: Data Structures & Algorithms. root node. level: internal node. edge.

CMSC 341 Lecture 14: Priority Queues, Heaps

CS 315 Data Structures mid-term 2

Chapter 22 Splay Trees

CSE373: Data Structures & Algorithms Lecture 6: Binary Search Trees. Linda Shapiro Spring 2016

Data Structures and Algorithms

Programming II (CS300)

A set of nodes (or vertices) with a single starting point

Balanced Search Trees

Search Trees. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Binary Search Trees

CSC148 Week 7. Larry Zhang

CS211, LECTURE 20 SEARCH TREES ANNOUNCEMENTS:

Recursion. Example 1: Fibonacci Numbers 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

Why Do We Need Trees?

Multi-way Search Trees! M-Way Search! M-Way Search Trees Representation!

CSE373: Data Structures & Algorithms Lecture 4: Dictionaries; Binary Search Trees. Kevin Quinn Fall 2015

Course Review for. Cpt S 223 Fall Cpt S 223. School of EECS, WSU

Second Examination Solution

Generic BST Interface

Binary Search Trees. Contents. Steven J. Zeil. July 11, Definition: Binary Search Trees The Binary Search Tree ADT...

Priority Queues. e.g. jobs sent to a printer, Operating system job scheduler in a multi-user environment. Simulation environments

CSE 431S Type Checking. Washington University Spring 2013

Announcements. Midterm exam 2, Thursday, May 18. Today s topic: Binary trees (Ch. 8) Next topic: Priority queues and heaps. Break around 11:45am

8. Binary Search Tree

INF2220: algorithms and data structures Series 1

Trees. Dr. Ronaldo Menezes Hugo Serrano Ronaldo Menezes, Florida Tech

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs

CSE 332: Data Structures & Parallelism Lecture 7: Dictionaries; Binary Search Trees. Ruth Anderson Winter 2019

Review: Trees Binary Search Trees Sets in Java Collections API CS1102S: Data Structures and Algorithms 05 A: Trees II

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

Algorithms. AVL Tree

COMP : Trees. COMP20012 Trees 219

CMPE 160: Introduction to Object Oriented Programming

CMSC 341 Lecture 15 Leftist Heaps

CSCI Trees. Mark Redekopp David Kempe

Chapter 20: Binary Trees

Binary Trees

CS 206 Introduction to Computer Science II

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees

Title Description Participants Textbook

Define the red- black tree properties Describe and implement rotations Implement red- black tree insertion

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree

Transcription:

CMPSCI 187: Programming With Data Structures Lecture #28: Binary Search Trees 21 November 2011

Binary Search Trees The Idea of a Binary Search Tree The BinarySearchTreeADT Interface The LinkedBinarySearchTree Class Adding an Element Removing An Element Array Implementations of Binary Search Trees

The Idea of a Binary Search Tree We want to be able to determine quickly (ideally in O(log n) time) whether a particular element is in our collection. Binary search did this for an array. But at the same time, we would like to be able to insert and delete elements without time-consuming shifts. In a binary search tree, every node has an element from an ordered base type. If a node n has element x, every element in the left subtree of n is less than x and every element in the right subtree is greater than x. Finding an element (or determining that it is not there) means following a path from the root to a leaf in the worst case. The time to do this is proportional to the depth of the tree. If the tree is balanced, this will be O(log n). In CMPSCI 311 (and a bit next lecture) we ll see ways to keep a tree balanced. But there is no reason that inserts and deletes should leave a balanced tree.

The BinarySearchTreeADT Interface Once we know that our binary tree is going to store elements from an ordered type, and use the binary search tree rules, we can set up the interface. We don t restrict T here, but we will cast T elements into Comparable<T>. If T only implements Comparable<? super T>, this won t work. The balanced binary tree classes will implement this same interface. public interface BinarySearchTreeADT<T> extends BinaryTreeADT<T> { public void addelement (T element); public T removeelement (T targetelement); public void removealloccurrrences (T targetelement); public T removemin( ); public T removemax( ); public T findmin( ); public T findmax( );

The LinkedBinarySearchTree Class We will inherit from the LinkedBinaryTree class, so that we have fields count and root, two constructors that we may use without changes, and the four iterator methods. We have a find method as well, but we don t want it -- it checks every element in the worst case, but we hope to use the ordering to do better. public class LinkedBinarySearchTree<T> extends LinkedBinaryTree<T> implements BinarySearchTreeADT <T> { public LinkedBinarySearchTree ( ) {super( );} public LinkedBinarySearchTree (T element) {super(element);} // add, remove, find methods to follow

Adding an Element: The Idea Our problem is to find a legal place to add a new leaf, containing the new element, in place of an existing null pointer. Although this code does not use recursion, the idea is recursive. To insert the new node into the subtree under node x, we compare the element against x and then insert the element into either the left or the right subtree of x. The base case is when we insert into an empty tree, and just make a new root containing the new element. What happens if the element is equal to an existing one? The test says to go to the left subtree of x if the new element is smaller than x s element. If it is equal, it goes into the right subtree. Of course if we didn t want to store duplicates, we could abort the add process when we discover the equality.

Adding an Element: Code Note the cast on line 3, which will fail if T is not an ordered class. public void addelement (T element) { BinaryTreeNode<T> temp = new BinaryTreeNode<T> (element); Comparable<T> comp = (Comparable<T>) element; if (isempty( )) root = temp; else {BinaryTreeNode<T> current = root; boolean added = false; while (!added) { if (comp.compareto (current.element) < 0) { if (current.left == null) { current.left = temp; added = true;} else current = current.left;} else if (current.right == null) { current.right = temp; added = true;} else current = current.right;}} count++;}

Removing an Element: The Idea The easy case is when the element to be removed is at a leaf -- we just remove it and nothing else needs to happen. If the element to be removed is a unary node, we just promote its only child into its position. Because everything satisfied the BST rules before, it still does. If the element to be removed has two children, we have to move either the largest element in the left subtree or the smallest element in the right subtree into its position. (It s arbitrary, we choose the latter.) But that element might not be a leaf, so we might not be done. Fortunately, it cannot have a left child (why?) and so we can promote its right child into its position.

Removing an Element: Code This is not all the code -- we need a method to fill in holes from deletions, and the search method won t fit on one page. public T removeelement (T target) throws ElementNotFoundException { T result = null; Comparable<T> comp = (Comparable<T>) target; if (!isempty( )) if (comp.equals (root.element)) { result = root.element; root = replacement (root); count--;} else {BinaryTreeNode<T> current, parent = root; boolean found = false; if (comp.compareto(root) < 0) current = root.left; else current = root.right; while (current!= null &&!found) { // see next page } if (!found) throw new ElementNotFoundException( );} return result;}

Removing an Element: More Code If we stumble across the target, we set found to be true, otherwise we move the variable current down the tree. Here and on the last page, we need a method to fill in holes, which is on the next page. while (current!= null) &&!found) if (target.equals (current.element)) { found = true; count--; result = current.element; if (current == parent.left) parent.left = replacement (current); else parent.right = replacement (current);} else {parent = current; if (comp.compareto (current.element) < 0) current = current.left; else current = current.right;}

Removing an Element: Still More Code This method finds a node that can safely be moved into the hole at node. In the general case this is the leftmost descendant of node s right child. protected BinaryTreeNode<T> replacement (BinaryTreeNode<T> node) { BinaryTreeNode<T> result = null; if ((node.left == null) && (node.right == null)) result = null; else if ((node.left!= null) && (node.right == null) result = node.left; else if ((node.left == null) && (node.right!= null) result = node.right; else {BinaryTreeNode<T> current = node.right, parent = node; while (current.left!= null) { parent = current; current = current.left;} if (node.right == current) current.left = node.left; else {parent.left = current.right; current.right = node.right; current.left = node.left;} result = current;} return result;}

Other Operations in LinkedBinarySearchTree To remove all occurrences of an element, we just keep removing them until there are no more, catching the final exception if needed. To remove the minimum element, we first find it by taking left children as long as they exist. If the minimum is a leaf, we just remove it -- if it is an internal node (with no left child) we remove it and promote its right child into its position. The removemax, findmin, and findmax operations are similar.

Array Implementations of Binary Search Trees Remember that we have two ways to implement a binary tree with an array. The first uses arithmetic operations to give each array index a parent (unless it is 0, the root), a left child, and a right child. The second replaces the pointers of the linked implementation with int variables storing an index. If we allow our tree to become unbalanced in the first version, we will expand our array to include room for a complete binary tree. Any indices that don t correspond to nodes actually in the tree will store null entries. This could use a lot of extra space if the tree is very unbalanced. L&C, in Section 10.3, have an array-based search tree that does some massive shifting when an element is removed. We won t look at this code. The other idea can be implemented with no wasted space if we keep a parent pointer for each node. Every add uses the next new array location, and on every remove we put the last entry into the hole created, updating the pointers.