04/24/09
16:48:00
1
37
CS61B:
Lecture 37
Friday, April 24, 2009
SPLAY TREES
===========
A splay tree is a type of balanced binary search tree.
Structurally, it is
identical to an ordinary binary search tree; the only difference is in the
algorithms for finding, inserting, and deleting entries.
All splay tree operations run in O(log n) time _on_average_, where n is the
number of entries in the tree.
Any single operation can take Theta(n) time in
the worst case.
But any sequence of k splay tree operations, with the tree
initially empty and never exceeding n items, takes O(k log n) worst-case time.
Although 2-3-4 trees make a stronger guarantee (_every_ operation on a 2-3-4
tree takes O(log n) time), splay trees have several advantages.
Splay trees
are simpler and easier to program.
Because of their simplicity, splay tree
insertions and deletions are typically faster in practice (sometimes by a
constant factor, sometimes asymptotically).
Find operations can be faster or
slower, depending on circumstances.
Splay trees really excel in applications where a small fraction of the entries
are the targets of most of the find operations, because they’re designed to
give especially fast access to entries that have been accessed recently.
Splay trees have become the most widely used data structure invented in the
last 25 years, because they’re the fastest type of balanced search tree for
many applications.
Tree Rotations
--------------
Like many types of balanced search
Y
X
trees, splay trees are kept balanced
/ \
rotate left
/ \
with the help of structural changes
X
^
<------------
^
Y
called _rotations_.
There are two
/ \ /C\
/A\ / \
types--a left rotation and a right
^
^
------------>
^
^
rotation--and each is the other’s
/A\/B\
rotate right
/B\/C\
reverse.
Suppose that X and Y are
binary tree nodes, and A, B, and C are subtrees.
A rotation transforms either
of the configurations illustrated above to the other.
Observe that the binary
search tree invariant is preserved:
keys in A are less than or equal to X;
keys in C are greater than or equal to Y; and keys in B are >= X and <= Y.
Rotations are also used in AVL trees and red-black trees, which are discussed
by Goodrich and Tamassia, but are not covered in this course.
Unlike 2-3-4 trees, splay trees are not kept perfectly balanced, but they tend
to stay reasonably well-balanced most of the time, thereby averaging O(log n)
time per operation in the worst case (and sometimes achieving O(1) average
running time in special cases).
Splay Tree Operations