28-07-2012, 09:51 AM
AVL-Trees
avl-tree.ppt (Size: 473 KB / Downloads: 109)
Balanced binary tree
The disadvantage of a binary search tree is that its height can be as large as N-1
This means that the time needed to perform insertion and deletion and many other operations can be O(N) in the worst case
We want a tree with small height
A binary tree with N node has height at least (log N)
Thus, our goal is to keep the height of a binary search tree O(log N)
Such trees are called balanced binary search trees. Examples are AVL tree, red-black tree.
AVL tree
Height of a node
The height of a leaf is 1. The height of a null pointer is zero.
The height of an internal node is the maximum height of its children plus 1
Note that this definition of height is different from the one we defined previously (we defined the height of a leaf as zero previously).
Rotations
Since an insertion/deletion involves adding/deleting a single node, this can only increase/decrease the height of some subtree by 1
Thus, if the AVL tree property is violated at a node x, it means that the heights of left(x) ad right(x) differ by exactly 2.
Rotations will be applied to x to restore the AVL tree property.
Insertion
First, insert the new key as a new leaf just as in ordinary binary search tree
Then trace the path from the new leaf towards the root. For each node x encountered, check if heights of left(x) and right(x) differ by at most 1.
If yes, proceed to parent(x). If not, restructure by doing either a single rotation or a double rotation [next slide].
For insertion, once we perform a rotation at a node x, we won’t need to perform any rotation at any ancestor of x.
Deletion
Delete a node x as in ordinary binary search tree. Note that the last node deleted is a leaf.
Then trace the path from the new leaf towards the root.
For each node x encountered, check if heights of left(x) and right(x) differ by at most 1. If yes, proceed to parent(x). If not, perform an appropriate rotation at x. There are 4 cases as in the case of insertion.
For deletion, after we perform a rotation at x, we may have to perform a rotation at some ancestor of x. Thus, we must continue to trace the path until we reach the root.
Rotations in deletion
There are 4 cases for single rotations, but we do not need to distinguish among them.
There are exactly two cases for double rotations (as in the case of insertion)
Therefore, we can reuse exactly the same procedure for insertion to determine which rotation to perform