Introduction to Computation and Problem Solving Class 28: Binary Search Trees Prof. Steven R. Lerman and Dr. V. Judson Harward.

Slides:



Advertisements
Similar presentations
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
Advertisements

The Dictionary ADT Definition A dictionary is an ordered or unordered list of key-element pairs, where keys are used to locate elements in the list. Example:
S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
Binary Search Trees Azhar Maqsood School of Electrical Engineering and Computer Sciences (SEECS-NUST)
Advanced Database Discussion B Trees. Motivation for B-Trees So far we have assumed that we can store an entire data structure in main memory What if.
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.
A Binary Search Tree Implementation Chapter Chapter Contents Getting Started An Interface for the Binary Search Tree Duplicate Entries Beginning.
© 2006 Pearson Addison-Wesley. All rights reserved11 B-1 Chapter 11 (continued) Trees.
Data Structures: Trees i206 Fall 2010 John Chuang Some slides adapted from Marti Hearst, Brian Hayes, or Glenn Brookshear.
Department of Computer Science University of Maryland, College Park
1 Trees. 2 Outline –Tree Structures –Tree Node Level and Path Length –Binary Tree Definition –Binary Tree Nodes –Binary Search Trees.
CSC 213 Lecture 7: Binary, AVL, and Splay Trees. Binary Search Trees (§ 9.1) Binary search tree (BST) is a binary tree storing key- value pairs (entries):
B + -Trees (Part 1) Lecture 20 COMP171 Fall 2006.
B + -Trees (Part 1). Motivation AVL tree with N nodes is an excellent data structure for searching, indexing, etc. –The Big-Oh analysis shows most operations.
Chapter 13 Binary Search Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define a binary search tree abstract.
General Trees and Variants CPSC 335. General Trees and transformation to binary trees B-tree variants: B*, B+, prefix B+ 2-4, Horizontal-vertical, Red-black.
A Binary Search Tree Implementation Chapter 25 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Marc Smith and Jim Ten Eyck
1 BST Trees A binary search tree is a binary tree in which every node satisfies the following: the key of every node in the left subtree is.
More Trees COL 106 Amit Kumar and Shweta Agrawal Most slides courtesy : Douglas Wilhelm Harder, MMath, UWaterloo
1 CSC 427: Data Structures and Algorithm Analysis Fall 2010 transform & conquer  transform-and-conquer approach  balanced search trees o AVL, 2-3 trees,
Binary Trees Chapter 6.
By : Budi Arifitama Pertemuan ke Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation.
CPSC 335 BTrees Dr. Marina Gavrilova Computer Science University of Calgary Canada.
B-Tree. B-Trees a specialized multi-way tree designed especially for use on disk In a B-tree each node may contain a large number of keys. The number.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
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:
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
Dictionaries CS 105. L11: Dictionaries Slide 2 Definition The Dictionary Data Structure structure that facilitates searching objects are stored with search.
1 B Trees - Motivation Recall our discussion on AVL-trees –The maximum height of an AVL-tree with n-nodes is log 2 (n) since the branching factor (degree,
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.
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
Trees CSCI Objectives Define trees as data structures Define the terms associated with trees Discuss the possible implementations of trees Analyze.
BINARY SEARCH TREE. Binary Trees A binary tree is a tree in which no node can have more than two children. In this case we can keep direct links to the.
Chapter 6 Binary Trees. 6.1 Trees, Binary Trees, and Binary Search Trees Linked lists usually are more flexible than arrays, but it is difficult to use.
Course: Programming II - Abstract Data Types Red-Black TreesSlide Number 1 Balanced Search Trees Binary Search Tree data structures can allow insertion,
Data Structures Balanced Trees 1CSCI Outline  Balanced Search Trees 2-3 Trees Trees Red-Black Trees 2CSCI 3110.
Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Binary Search Trees Binary Search Trees (BST)  the tree from the previous slide is a special kind of binary tree called a binary.
1 Chapter 10 Trees. 2 Definition of Tree A tree is a set of linked nodes, such that there is one and only one path from a unique node (called the root.
2-3 Trees, Trees Red-Black Trees
Binary Search Trees (10.1) CSE 2011 Winter November 2015.
1 Trees, Trees, and More Trees. 2 By looking at forests of terms, awesome animations, and complete examples, we hope to get at the root of trees. Hopefully,
© 2004 Goodrich, Tamassia Binary Search Trees1 CSC 212 Lecture 18: Binary and AVL Trees.
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
Lecture1 introductions and Tree Data Structures 11/12/20151.
Dictionaries CS /02/05 L7: Dictionaries Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
3.1. Binary Search Trees   . Ordered Dictionaries Keys are assumed to come from a total order. Old operations: insert, delete, find, …
1 Chapter 7 Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation of the binary search tree.
Binary Search Trees (BSTs) 18 February Binary Search Tree (BST) An important special kind of binary tree is the BST Each node stores some information.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
1 CompSci 105 SS 2006 Principles of Computer Science Lecture 17: Heaps cont.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Dictionaries CS 110: Data Structures and Algorithms First Semester,
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 20 Ordered.
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
UNIT III TREES.
Binary Search Tree (BST)
Lecture 22 Binary Search Trees Chapter 10 of textbook
Trees.
i206: Lecture 13: Recursion, continued Trees
Binary Tree and General Tree
Binary Search Trees.
(2,4) Trees 2/15/2019 (2,4) Trees (2,4) Trees.
Binary Search Trees 7/16/2009.
(2,4) Trees (2,4) Trees (2,4) Trees.
B-Trees.
Trees.
Presentation transcript:

Introduction to Computation and Problem Solving Class 28: Binary Search Trees Prof. Steven R. Lerman and Dr. V. Judson Harward

Binary Search Trees In the previous lecture, we defined the concept of binary search tree as a binary tree of nodes containing an ordered key with the following additional property. The left subtree of every node (if it exists) must only contain nodes with keys less than or equal to the parent and the right subtree (if it exists) must only contain nodes with keys greater than or equal to the parent. We saw that performing an inorder traversal of such a tree is would visit each node in order.

Goals We are going to implement a binary search tree with the usual data structure operations and then critique the implementation. Generalizations of the binary search tree drive many important applications, including commercial databases. The implementation will give you a feel for tree methods that tend to be more "visual" or "topological" than array or list implementations.

Keys and Values If binary search trees are ordered, then they must be ordered on some key possessed by every tree node. A node might contain nothing but the key, but it's often useful to allow each node to contain a key and a value. The key is used to look up the node. The value is extra data contained in the node indexed by the key.

Maps Such data structures with key/value pairs are usually called maps. As an example, consider the entries in a phone book as they might be entered in a binary search tree. The subscriber name, last name first, serves as the key, and the phone number serves as the value.

Key and Value Type Sometimes you may not need the value. But if one node has a value, you probably want to supply one for every node. We also haven't specified the type of the key and value. They can be of any class you want, but all nodes should possess keys that are instances of the same class and values that are instances of the same class. Keys and values do not have to be the same type. Keys and values will be handled as Objects by our tree implementation except when we need to compare them.

Duplicate Keys Do we allow the tree to contain nodes with identical keys? There is nothing in the concept of a binary search tree that prevents duplicate keys. In the interface that we will implement, we use the keys to access the values. If we allowed duplicate keys, we wouldn't be able to distinguish between multiple nodes possessing the same key. Thus, in this implementation, duplicate keys will not be allowed. Duplicate values associated with different keys are legal.

SortedMap Interface public interface SortedMap { // keys may not be null but values may be public boolean isEmpty(); public void clear(); public int size(); public Object get( Object key ); public Object firstKey(); public Object lastKey(); public Object remove( Object key ); public Object put( Object key, Object value ); public MapIterator iterator(); }

SortedMap Notes get(), firstKey(), lastKey() all return the appropriate values and leave the key value pair in the map. firstKey() and lastKey() return null if the map is empty remove() returns the value if the key is present; otherwise it returns null put(): if the key is not in the map, insert the new key/value pair; if the key is already present, return the old value, and replace the old value with the new one in the map

MapIterator Interface public interface MapIterator { public boolean hasNext(); public Object next() throws NoSuchElementException; public Object remove() throws IllegalStateException; public Object key() throws IllegalStateException; public Object getValue() throws IllegalStateException; public Object setValue( Object value ) throws IllegalStateException; }

Comparator If keys are arbitrary objects, how can you order them? The user can supply his own Comparator public interface Comparator { // Neither o1 nor o2 may be null public int compare(Object o1, Object o2); } // e.g., compare( Integer(5), Integer(7)) < 0 // compare( Integer(5), Integer(5)) == 0

StringComparator public class StringComparator implements Comparator { public int compare(Object o1, Object o2) { return ((String) o1).compareTo((String) o2); } BinarySearchTree btree = new BinarySearchTree( new StringComparator() );

Comparable Interface In recent versions of the JDK, the wrapper classes for builtin types all implement a separate Comparable interface: public interface Comparable { public int compareTo(Object o); } Since String implements the Comparable interface, we don't need to implement the special StringComparator. The compareTo() method returns ints with the same sense as the Comparator interface.

Implementing BinarySearchTree We will have separate tree and node classes forBinarySearchTree. We will use a private static inner class for the node class, Branch, just as we did for the SLink class in SLinkedList. public class BinarySearchTree implements SortedMap { private Branch root = null; private int length = 0; private Comparator comparator = null;

Branch Inner Class Branch holds links to its parent node as well as left and right subtrees. This will make some operations like deleting a node much more efficient. static private class Branch { private Branch left = null; private Branch right = null; private Branch parent = null; private Object key; private Object value = null;

Simple Methods public BinarySearchTree( Comparator c ) { comparator = c; } public BinarySearchTree() { this( null ); } public void clear() { root = null; length = 0; } public boolean isEmpty() { return ( root == null ); }

firstKey() Method public Object firstKey() { if ( root == null ) return null; else return root.first().key; }In Branch:Branch first() { Branch f = this; while ( f.left != null ) { f = f.left; } return f; }

firstKey() in Action

get() Method public Object get( Object k ) { Branch b = find( k ); return ( b == null ) ? null : b.value; } private Branch find( Object k ) { Branch b = root; int c; while (b != null && (c=compare( k, b.key )) != 0) { if ( c < 0 ) b = b.left; else b = b.right; } return b; }

get() in Action

compare() Method private int compare(Object k1, Object k2) { if ( k1 == null || k2 == null ) throw new IllegalArgumentException( "Null key now allowed" ); // if there is a comparator, use it if ( comparator != null ) return comparator.compare( k1, k2 ); else { return ((Comparable)k1).compareTo(k2); } }

put() Strategy Our strategy is to look for the key supplied as an argument. If we find it, we return the old value after replacing it with the new one. While searching for the node, shadow our search by keeping a reference to the parent of the current node. If we don’t find the node, the search ends when we arrive at a null branch. In this case, the parent reference will identify the parent of the new inserted node.

put() in Action

put() Method, 1 public Object put(Object k, Object v) { Branch p = null; Branch b = root; int c = 0; // find node with key k retaining ref p to parent while ( b != null ) { p = b; c = compare( k, b.key ); if ( c == 0 ) { // found it; insert new value, return old Object oldValue = b.value; b.value = v; return oldValue; } else if ( c < 0 ) b = b.left; else b = b.right; }

// Key k doesn't exist in tree;// insert new node below p(arent)Branch newBranch = new Branch( k, v, p );length++;if ( p == null ) { root = newBranch; } else { // c still holds last comparison if ( c < 0 ) p.left = newBranch; else p.right = newBranch; } return null; } put() Method, 2

delete() Strategy remove() calls delete() to do most of the work. When we delete a node from a binary search tree, we must ensure that the resulting structure (1) is still a tree, and (2) the tree still obeys the rule of a binary search tree. The rule requires that for every node, the keys in the left subtree if present precede the key of the node which must precede the keys in the right subtree.

delete() Cases, 1 There are three deletion cases we must consider: 1.The deleted node has no children, e.g., node 29 below The deleted node has one child, e.g., node 7 below The deleted node has two children, e.g., node 25 below

delete(), No Children

delete(), 1 Child

delete(), 2 Children

delete(), 2 Children Strategy In the last case, that of two children, the problem is more serious since the tree is now in three parts. The solution starts by realizing that we can minimize the ordering problem by stitching the tree back together using the node immediately preceding or following the deleted node in inorder sequence. These are known as the predecessor and successor nodes.

Using the Successor Node Let's choose the successor node. The successor of a node with a right subtree will be the first() node of that subtree. If we replace the deleted node by its successor, then all ordering conditions will be met. But what about the successor's children. The successor of a node with two children can have at most one child (a right child). If it had a left subtree, the node couldn't be the successor since members of the left subtree follow the deleted node but precede the successor. Since the successor can have at most one subtree, we can move the successor up to replace the node we want to remove and relink its right subtree, if present, as in the second case above.

delete(), find successor

delete(), replace successor 1

delete(), replace successor 2

delete(), replace successor 3

The Efficiency of Binary Search It makes intuitive sense that the basic operations on a binary search tree should require O(h) time where h is the height of the tree. It turns out that the height of a balanced binary tree is roughly log2(n) where n is the number of elements if the tree remains approximately balanced. It can be proved that if keys are randomly inserted in a binary search tree, this condition will be met, and the tree will remain adequately enough balanced so that search and insertion time will approximate O(log n).

Tree Balance There are some extremely simple and common cases, however, where keys will not be inserted in random order. Consider what will happen if you insert keys into a search tree from a sorted list. The tree will assume a degenerate form equivalent to the source list and search and insertion times will degrade to O(n). There are many variants of trees, e.g., red- black trees, AVL trees, B-trees, that try to solve this problem by rebalancing the tree after operations that unbalance it.

Keys Inserted in Order