Lecture Notes on Binary Search Trees

Similar documents
Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees

Lecture 15 Notes Binary Search Trees

Lecture 15 Binary Search Trees

Lecture 16 Notes AVL Trees

Midterm II Exam Principles of Imperative Computation Frank Pfenning. March 31, 2011

Lecture Notes on Priority Queues

Lecture 16 AVL Trees

You must print this PDF and write your answers neatly by hand. You should hand in the assignment before recitation begins.

Lecture 18 Restoring Invariants

Lecture Notes on Tries

Lecture 17 Notes Priority Queues

Lecture Notes on Tries

Lecture Notes on Interfaces

Lecture 17 Priority Queues

Midterm 2 Exam Principles of Imperative Computation. Tuesday 31 st March, This exam is closed-book with one sheet of notes permitted.

Trees. Chapter 6. strings. 3 Both position and Enumerator are similar in concept to C++ iterators, although the details are quite different.

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

Lecture Notes on Memory Layout

Lecture 10 Notes Linked Lists

Sorting L7.2 Recall linear search for an element in an array, which is O(n). The divide-and-conquer technique of binary search divides the array in ha

Lecture Notes on Binary Decision Diagrams

Midterm I Exam Principles of Imperative Computation Frank Pfenning. February 17, 2011

Lecture Notes on Queues

Lecture 10 Notes Linked Lists

You must include this cover sheet. Either type up the assignment using theory5.tex, or print out this PDF.

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

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

Lecture Notes on Quicksort

Lecture Notes on Quicksort

Lecture 13 Notes Sets

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

Lecture 5. Treaps Find, insert, delete, split, and join in treaps Randomized search trees Randomized search tree time costs

Binary Trees and Binary Search Trees

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

Lecture 16 Notes AVL Trees

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

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

Fall, 2015 Prof. Jungkeun Park

CSE100. Advanced Data Structures. Lecture 8. (Based on Paul Kube course materials)

: Principles of Imperative Computation Victor Adamchik. Practice Exam - I

Chapter 20: Binary Trees

Chapter 4: Trees. 4.2 For node B :

Lecture Notes on AVL Trees

CS102 Binary Search Trees

Lecture 13 Notes Sets

Algorithms. Deleting from Red-Black Trees B-Trees

Advanced Set Representation Methods

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

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17

Lecture 7 Quicksort : Principles of Imperative Computation (Spring 2018) Frank Pfenning

Lecture Notes on Tries

Lecture Notes on Generic Data Structures

Lecture Notes on Queues

ITI Introduction to Computing II

Data Structures Lesson 7

Binary Search Trees Treesort

Lecture Notes on Dynamic Programming

DATA STRUCTURES AND ALGORITHMS. Hierarchical data structures: AVL tree, Bayer tree, Heap

CSCI-1200 Data Structures Spring 2015 Lecture 20 Trees, Part III

ITI Introduction to Computing II

COMP Analysis of Algorithms & Data Structures

I2206 Data Structures TS 6: Binary Trees - Binary Search Trees

CMSC 341 Lecture 14: Priority Queues, Heaps

Data Structures and Algorithms for Engineers

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

Recitation 9. Prelim Review

CmpSci 187: Programming with Data Structures Spring 2015

Algorithms, Spring 2014, CSE, OSU Lecture 2: Sorting

Algorithms. AVL Tree

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

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

CS 315 Data Structures mid-term 2

Lecture Notes for Advanced Algorithms

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

CSE 373 Winter 2009: Midterm #1 (closed book, closed notes, NO calculators allowed)

COMP Analysis of Algorithms & Data Structures

Lecture Notes on Generic Data Structures

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

Lecture 4 Searching Arrays

Lecture Notes on Linear Search

Second Examination Solution

- 1 - Handout #22S May 24, 2013 Practice Second Midterm Exam Solutions. CS106B Spring 2013

CSCI-1200 Data Structures Fall 2014 Lecture 18 Trees, Part III

Lecture 13 Hash Dictionaries

Week 10. Sorting. 1 Binary heaps. 2 Heapification. 3 Building a heap 4 HEAP-SORT. 5 Priority queues 6 QUICK-SORT. 7 Analysing QUICK-SORT.

A6-R3: DATA STRUCTURE THROUGH C LANGUAGE

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1

CSCI-1200 Data Structures Fall 2018 Lecture 19 Trees, Part III

Section 4 SOLUTION: AVL Trees & B-Trees

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

CSCI Trees. Mark Redekopp David Kempe

Binary Search Trees. Analysis of Algorithms

CMSC 341 Lecture 15 Leftist Heaps

Lecture 8 Data Structures

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

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

You must print this PDF and write your answers neatly by hand. You should hand in the assignment before recitation begins.

Week 10. Sorting. 1 Binary heaps. 2 Heapification. 3 Building a heap 4 HEAP-SORT. 5 Priority queues 6 QUICK-SORT. 7 Analysing QUICK-SORT.

Transcription:

Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning Lecture 17 1 Introduction In the previous two lectures we have seen how to exploit the structure of binary trees in order to efficiently implement priority queues. A priority queue is an abstract type where we can insert an arbitrary element and delete the minimal element. The O(log(n)) worst-case time for insert and delete arose from using a balanced binary tree, which has maximal depth log(n) + 1 for storing n elements. With binary search trees we try to obtain efficient insert and search times for associative arrays, which we have previously implemented as hash tables. Even though the operations turn out to be quite different from those on priority queues, we will indeed eventually be able to achieve O(log(n)) worst-case asymptotic complexity for insert and search. This also extends to delete, although we won t discuss that operation in lecture. 2 The Ordering Invariant At the core of binary search trees is the ordering invariant. Ordering Invariant. At any node with key k in a binary search tree, all keys of the elements in the left subtree are strictly less than k, while all keys of the elements in the right subtree are strictly greater than k. This implies that no key occurs more than once in a tree, and we have to make sure our insertion function maintains this invariant.

Binary Search Trees L17.2 If our binary search tree were perfectly balanced, that is, had the same number of nodes on the left as on the right for every subtree, then the ordering invariant would ensure that search for an element with a given key has asymptotic complexity O(log(n)), where n is the number of elements in the tree. Why? When searching for a given key k in the tree, we just compare k with the key k of the entry at the root. If they are equal, we have found the entry. If k < k we recursively search in the left subtree, and if k < k we recursively search in the right subtree. This is just like binary search, except that instead of an array we traverse a tree data structure. 3 The Interface We assume that the client defines a type elem of elements and a type key of keys, as well as functions to extract keys from elements and to compare keys. Then the implementation of binary search trees will provide a type bst and functions to insert an element and to search for an element with a given key. /* Client-side interface declarations */ typedef key; typedef * elem; /* NULL must be an elem */ key elem_key(elem e); int compare(key k1, key k2); /* Library-side interface declarations */ typedef struct bst* bst; bst bst_new(); void bst_insert(bst B, elem e) /* replace if elem with same key as x in B */ //@requires e!= NULL; ; elem bst_search(bst B, key k); /* return NULL if not in tree */ We stipulate that elem is some form of pointer type so we can return null if no element with the given key can be found. Generally, some more operations may be requested at the interface, such as the number of elements in the tree or a function to delete an element with a given key. The compare function provided by the client is different from the equality function we used for hash tables. For binary search trees, we actually need to compare keys k 1 and k 2 and determine if k 1 < k 2, k 1 = k 2, or

Binary Search Trees L17.3 k 1 > k 2. A standard approach to this in imperative languages is for a comparison function to return an integer r, where r < 0 means k 1 < k 2, r = 0 means k 1 = k 2, and r > 0 means k 1 > k 2. 4 A Representation with Pointers Unlike heaps, we cannot easily represent binary search trees with arrays and keep them balanced in the way we preserved the heap invariant. This is because with heaps where was a lot of flexibility where to insert new elements, while with binary search trees the position of the new element seems rather rigidly determined 1. So we will use a pointer-based implementation where every node has two pointers: one to its left child and one to its right child. A missing child is represented as NULL, so a leaf just has two null pointers. typedef struct tree* tree; struct tree { elem data; tree left; tree right; ; As usual, we have a header which in this case just consists of a pointer to the root of the tree. We often keep other information associated with the data structure in these headers, such as the size. struct bst { tree root; ; 5 Searching for a Key In this lecture, we will implement insertion and search first before considering the data structure invariant. This is not the usual way we proceed, but it turns out finding a good function to test the invariant is a significant challenge meanwhile we would like to exercise programming with pointers in a tree a little. For now, we just assume we have two functions 1 although we will see next lecture that this is not strictly true

Binary Search Trees L17.4 bool is_ordtree(tree T); bool is_bst(bst B); Search is quite straightforward, implementing the informal description above. Recall that compare(k1,k2) returns 1 if k 1 < k 2, 0 if k 1 = k 2, and 1 if k 1 > k 2. elem tree_search(tree T, key k) //@requires is_ordtree(t); //@ensures \result == NULL compare(elem_key(\result), k) == 0; { if (T == NULL) return NULL; int r = compare(k, elem_key(t->data)); if (r == 0) return T->data; else if (r < 0) return tree_search(t->left, k); else //@assert r > 0; return tree_search(t->right, k); elem bst_search(bst B, key k) //@requires is_bst(b); //@ensures \result == NULL compare(elem_key(\result), k) == 0; { return tree_search(b->root, k); We chose here a recursive implementation, following the structure of a tree, but in practice an iterative version may be preferable (see Exercise??). We can check the invariant: if T is ordered when tree_search(t) is called (and presumably is_bst would guarantee that), then both subtrees should be ordered as well and the invariant is preserved. 6 Inserting an Element Inserting an element is almost as simple. We just proceed as if we are looking for the key of the given element. If we find a node with that key, we just overwrite its data field. If not, we insert it in the place where it would have been, had it been there in the first place. This last clause, however, creates

Binary Search Trees L17.5 a small difficulty. When we hit a null pointer (which indicates the key was not already in the tree), we cannot just modify NULL. Instead, we return the new tree so that the parent can modify itself. tree tree_insert(tree T, elem e) //@requires is_ordtree(t); //@ensures is_ordtree(\result); { assert(e!= NULL); /* cannot insert NULL element */ if (T == NULL) { /* create new node and return it */ T = alloc(struct tree); T->data = e; T->left = NULL; T->right = NULL; return T; int r = compare(elem_key(e), elem_key(t->data)); if (r == 0) T->data = e; /* modify in place */ else if (r < 0) T->left = tree_insert(t->left, e); else //@assert r > 0; T->right = tree_insert(t->right, e); return T; For the same reason as in tree_search, we expect the subtrees to be ordered when we make recursive calls. The result should be ordered for analogous reasons. The returned subtree will also be useful at the root. void bst_insert(bst B, elem x) //@requires is_bst(b); //@ensures is_bst(b); { B->root = tree_insert(b->root, x); return;

Binary Search Trees L17.6 7 Checking the Ordering Invariant When we analyze the structure of the recursive functions implementing search and insert, we are tempted to say that a binary search is ordered if either it is null, or the left and right subtrees have a key that is smaller. This would yield the following code: bool is_ordtree(tree T) { key k; if (T == NULL) return true; // an empty tree is a BST k = elem_key(t->data); return (T->left == NULL (compare(elem_key(t->left->data), k) < 0 && is_ordtree(t->left))) && (T->right == NULL (compare(k, elem_key(t->right->data)) < 0 && is_ordtree(t->right))); While this should always be true for a binary search tree, it is far weaker than the ordering invariant stated at the beginning of lecture. Before reading on, you should check your understanding of that invariant to exhibit a tree that would satisfy the above, but violate the ordering invariant.

Binary Search Trees L17.7 There is actually more than one problem with this. The most glaring one is that following tree would pass this test: 7 5 1 9 Even though, locally, the key of the left node is always smaller and on the right is always bigger, the node with key 9 is in the wrong place and we would not find it with our search algorithm since we would look in the right subtree of the root. An alternative way of thinking about the invariant is as follows. Assume we are at a node with key k. 1. If we go to the left subtree, we establish an upper bound on the keys in the subtree: they must all be smaller than k. 2. If we go to the right subtree, we establish a lower bound on the keys in the subtree: they must all be larger than k. The general idea then is to traverse the tree recursively, and pass down an interval with lower and upper bounds for all the keys in the tree. The following diagram illustrates this idea. We start at the root with an unrestricted interval, allowing any key, which is written as (, + ). As usual in mathematics we write intervals as (x, z) = {y x < y and y < z. At the leaves we write the interval for the subtree. For example, if there were a left subtree of the node with key 7, all of its keys would have to be in the

Binary Search Trees L17.8 interval (5, 7). (, + ) 9 (, 9) 5 (, 5) (5, 9) (9, + ) 7 (5, 7) (7, 9) The only difficulty in implementing this idea is the unbounded intervals, written above as and +. Here is one possibility: we pass not just the key, but the particular element which bounds the tree from which we can extract the element. This allows us to pass null in case there is no lower or upper bound. bool is_ordered(tree T, elem lower, elem upper) { if (T == NULL) return true; if (T->data == NULL) return false; key k = elem_key(t->data); if (!(lower == NULL compare(elem_key(lower),k) < 0)) return false; if (!(upper == NULL compare(k,elem_key(upper)) < 0)) return false; return is_ordered(t->left, lower, T->data) && is_ordered(t->right, T->data, upper); bool is_ordtree(tree T) { /* initially, we have no bounds - pass in NULL */ return is_ordered(t, NULL, NULL); bool is_bst(bst B) { return B!= NULL && is_ordtree(b->root);

Binary Search Trees L17.9 8 The Shape of Binary Search Trees We have already mentioned that a balanced binary search trees has good properties, such as logarithmic time for insertion and search. The question is if binary search trees will be balanced. This depends on the order of insertion. Consider the insertion of numbers 1, 2, 3, and 4. If we insert them in increasing order we obtain the following trees in sequence. 2 2 2 3 3 4 Similarly, if we insert them in decreasing order we get a straight line along, always going to the left. If we instead insert in the order 3, 1, 4, 2, we obtain the following sequence of binary search trees: 3 3 3 3 4 4 2 Clearly, the last tree is much more balanced. In the extreme, if we insert elements with their keys in order, or reverse order, the tree will be linear, and search time will be O(n) for n items. These observations mean that it is extremely important to pay attention to the balance of the tree. We will discuss ways to keep binary search trees balanced in the next lecture.

Binary Search Trees L17.10 Exercises Exercise 1 Rewrite tree_search to be iterative rather than recursive. Exercise 2 Rewrite tree_insert to be iterative rather than recursive. [Hint: The difficulty will be to update the pointers in the parents when we replace a node that is null. For that purpose we can keep a trailing pointer which should be the parent of the note currently under consideration.]