




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





CLRS Chapter 10, 12.1-
Example
time (mins) now x x x x
Figure 1: Runway Reservation System Example
Let R denote the reserved landing times: R = (41, 46 , 49 , 56) and k = 3
Request for time: 44 not allowed (46 ∈ R) 53 OK 20 not allowed (already past) | R |= n
Goal: Run this system efficiently in O(lg n) time
Algorithm
Keep R as a sorted list.
init: R = [ ] req(t): if t < now: return "error" for i in range (len(R)): if abs(t-R[i]) < k: return "error" R.append(t) R = sorted(R) land: t = R[0] if (t != now) return error R = R[1: ] (drop R[0] from R)
insert 49
insert 79
insert 46
insert 41 insert 64
root all elements > 49 off to the right, in right subtree all elements < 49, go into left subtree
Figure 2: Binary Search Tree
Properties
Each node x in the binary tree has a key key(x). Nodes other than the root have a parent p(x). Nodes may have a left child lef t(x) and/or a right child right(x). These are pointers unlike in a heap. The invariant is: for any node x, for all nodes y in the left subtree of x, key(y) ≤ key(x). For all nodes y in the right subtree of x key(y) ≥ key(x).
Insertion: insert(val)
Follow left and right pointers till you find the position (or see the value), as illustrated in Figure 2. We can do the “within k = 3” check for runway reservation during insertion. If you see on the path from the root an element that is within k = 3 of what you are inserting, then you interrupt the procedure, and do not insert.
Finding a value in the BST if it exists: find(val)
Follow left and right pointers until you find it or hit NIL.
Finding the minimum element in a BST: findmin()
Key is to just go left till you cannot go left anymore.
Figure 3: Delete-Min: finds minimum and eliminates it
Complexity
All operations are O(h) where h is height of the BST. Finding the next larger element: next-larger(x)
Note that x is a node in the BST, not a value. next-larger(x)
if right child not NIL, return minimum(right) else y = parent(x) while y not NIL and x = right(y) x = y; y = parent(y) return(y);
See Fig. 4 for an example. What would next-larger(find(46)) return?
Figure 4: next-larger(x)
subtree
subtree
Figure 6: Augmentation Algorithm Example
All the Python code for the Binary Search Trees discussed here are available at this link
Height h of the tree should be O(lg n).
Figure 7: Insert into BST in sorted order
The tree in Fig. 7 looks like a linked list. We have achieved O(n) not O(lg n)!!
Balanced BSTs to the rescue in the next lecture!
MIT OpenCourseWare http://ocw.mit.edu
6.00 6 Introduction to Algorithms Fall 2011
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.