---------------------------------------------------------------------------
COMP 731 - Data Struc & Algorithms - Lecture 21 - Thursday, August 17, 2000
---------------------------------------------------------------------------
Today:
o Size of an AVL tree
o Splay trees
Unfinished business:
recall:
Definition: An AVL tree is a binary search tree T such that for all nodes
x in tree,
| height(left(x)) - height(right(x)) | <= 1
Claim: this is enough to ensure that the tree has exponentially many
nodes in its height.
Proof: let G(n) = the size of a smallest AVL tree of height n.
What should such a tree look like?
root
a smallest a smallest
AVL tree of AVL tree of
height n-1 height n-2
SO
G(n) = G(n-1) + G(n-2) + 1 (the +1 is for the root) for n>=2
G(0) = 0
G(1) = 1
Looks like the Fibonacci series, no?
0 1 2 4 7 12 20 33 54 ...
1 1 2 3 5 8 12 20 32
In fact, G(n) > F(n), for n>=1, where we index
F(n) = F(n-1) + F(n-2)
F(0) = F(1) = 1
And we have already shown that F(n) >= phi^n,
where phi = (1+sqrt(5)) / 2 = 1.618...
Conclude: AVL tree are "balanced" enough. The question is how to do insertions
and deletions in a way that preserves the AVL-property!
Splay trees:
We'll only describe insertions (deletions are described in various books, however).
Basic operation: a ROTATION
p x
/ \ / \
x Tr3 ======> Tr1 p
/ \ / \
Tr1 Tr2 Tr2 Tr3
p x
/ \ / \
Tr1 x ======> p Tr3
/ \ / \
Tr2 Tr3 Tr1 Tr2
Check: this preserves the BST ordering!
We will also need DOUBLE ROTATIONS as with AVL tree (zig-zag)
g x
/ \ / \
Tr1 p g p
/ \ ====> / \ / \
x Tr4 Tr1 Tr2 Tr3 Tr4
/ \
Tr2 Tr3
g x
/ \ / \
p Tr4 p g
/ \ =====> / \ / \
Tr1 x Tr1 Tr2 Tr3 Tr4
/ \
Tr2 Tr3
And we'll need a different kind of double rotation (zig-zig):
g x
/ \ / \
p Tr4 Tr1 p
/ \ =====> / \
x Tr3 Tr2 g
/ \ / \
Tr1 Tr2 Tr3 Tr4
g x
/ \ / \
Tr1 p p Tr4
/ \ ======> / \
Tr2 x g Tr3
/ \ / \
Tr3 Tr4 Tr1 Tr2
The insert and find algorithms are simple: after inserting or finding
the node, splay it to the root, where
splay(x): work your way up to root, doing double rotations (zig-zig
or zig-zag) until you get there, or until you get to be
the root's child, whence you do a single rotation.
Do an example of inserting nodes 1,2,3,4,5,6,7, and now accessing
(and node