This preview shows pages 1–2. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: Illinois Institute of Technology Department of Computer Science Lecture 7: February 11, 2009 CS 430 Introduction to Algorithms Spring Semester, 2009 1 Binary search trees Sorted arrays are attractive that we can use binary search to locate any element in (log n ) time. Unfortu- nately, this comes at a significant cost: insertion or deletion of an element requires ( n ) time. With a linked list, locating an element requires ( n ) time, but insertion or deletion requires only (1) time. We can use trees to combine these benefits. Each node in a binary tree contains a record (our examples here assume that the record is a number) and has pointers to two children, one left child and one right child. In particular, a binary search tree is lexicographic ; that is, the values in the left subtree are all less than the value at the root and the values in the right subtree are all greater than the value at the root. 1.1 Basic operations 1.1.1 Search Searching for an element x in a binary search tree is simple: If the tree is empty, then x is not in the tree. If the tree is not null, say the element stored at the root is r . If x = r , the root contains the element and the search is complete. If x < r then x must be in the left subtree if it is in the tree at all. Thus, we recursively search for x in the left subtree. Likewise, if x > r , we recursively search of x in the right subtree. If the tree is nicely balanced, this runs in (log n ) time. If the tree is badly skewed it takes ( n ) time, no better than a linked list. In general, it runs in time ( height ( T )), where height ( T ) is the height of tree...
View Full Document