---------------------------------------------------------------------------
COMP 731 - Data Struc & Algorithms - Lecture 20 - Tuesday, August 16, 2000
---------------------------------------------------------------------------
Today:
o Binary search trees, lecture 2
Not mentioned last lecture:
Minor problem: case 3 will tend to "skew" the tree:
since we are alway replacing a node x with a node from the RIGHT subtree of
x, the tree will start to get left-heavy. One possibility is to ignore this.
Another possibility is to randomly select to replace x by the successor
(right and the left as far as possible) or the predecessor (left and then
right as far as possible). A simpler possibility (no pseudorandom random-number
generation needed) is to ALTERNATE between these two possibilities.
Tree traversals:
Describe right-hand-on-the-edge traversal
Describe breadth-first traversal (uses a QUEUE), and
Depth-first traversals:
preorder(x): visit(x) preorder(left(x)) preorder(right(x))
inorder(x): inorder(left(x)) visit(x) inorder(right(x))
postorder(x): postorder(left(x)) postorder(right(x)) visit(x)
Draw a tree and illustrate....
......
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
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:
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
We insert the item new-item and march up the tree looking for a
place of imbalance. Suppose there is an imbalance at p: p
\
x
(Too deep)
Usually we will rotate about p and this will fix the problem.
\
x
However, if the newly inserted item is between p and x, we will have
to do a double rotation. As an example (follow Weiss) we build the
tree by inserting:
1 2 3 4 5 6 7 15 14 13 12 11 10 9 8 8.5