AVL Trees: Elementary Maths For GMT 1
AVL Trees: Elementary Maths For GMT 1
v
3 8
z
4
AVL Trees
AVL Trees 3
Height of an AVL Tree
Property: The height of an AVL tree storing n keys is O(log n)
Proof: Let us bound N(h): the minimum number of internal
nodes of an AVL tree of height h
N(1) = 1 and N(2) = 2
N(h) > 2i N(h-2i)
Choose i = h/2 -1:
N(h) > 2 h/2-1 N(h-2(h/2 -1)) = 2 h/2-1 N(2) = 2 h/2-1 2
AVL Trees 4
Insertion in an AVL Tree
Insertion is as in a binary search tree: always done by expanding
an external node
imbalance
44 Example: insert 54 44
17 78
17 78
32 50 88
32 50 88
48 62
48 62
54
AVL Trees 5
Imbalance after Insertion
44
Let w be the inserted node
17 78
z z be the first unbalanced ancestor
y of w
y be the child of z with higher
32 50 88
height (must be an ancestor of w)
x be the child of y with higher
48 62
x height (must be an ancestor of w;
or w itself)
54
w
AVL Trees 6
Trinode Restructuring
Perform the rotations needed to make y the topmost node of the
three.
z
case 1: single rotation y
y
z x
T0
x
T1 T0 T1 T2 T3
T2 T3
AVL Trees 7
Trinode Restructuring
symmetric case y
y
T3
x z
x
T2
T0 T1 T0 T1 T2 T3
AVL Trees 8
Trinode Restructuring
z
x
case 2: double rotation
y
T0 z y
x
T3
T0 T1 T2 T3
T1 T2
AVL Trees 9
Trinode Restructuring
z x
symmetric case
y y z
T3
x
T0
T0 T1 T2 T3
T1 T2
AVL Trees 10
Removal in an AVL Tree
Removal begins as in a binary search tree, which means the
node removed will become an empty external node
imbalance
44 Example: delete 32 44
17 62 17 62
32 50 78
50 78
48 54 88 48 54 88
AVL Trees 11
Imbalance after Removal
z 44 Let w be the parent of the
removed node
w y Let z be the first unbalanced
17 62
ancestor of w
Let y be the child of z with higher
50 78 x height (is now not an ancestor of
w)
Let x be
48 54 88
the child of y with higher height,
if heights are different, or
the child of y on the same side
as y, if heights are equal
AVL Trees 12
Rebalancing after a Removal
Perform rotations to make y the topmost of the three.
As this restructuring may upset the balance of another node
higher in the tree, we must continue checking for balance until
the root of T is reached
z 44 62
w 17 62 y 44 78
50 78 x 17 50 88
48 54 88 48 54
AVL Trees 13
Repeated Rebalancing
44 44
17 78 17 w=z 78
y
14 32 50 88 32 50 88
25 48 62 93 25 x 48 62 93
54 54
Example: delete 14
AVL Trees 14
Repeated Rebalancing
44
25 78
17
25 32 50 88
48 62 93
54
AVL Trees 15
Running Times for AVL Trees
Finding a value takes O(log n) time
because height of tree is always O(log n)
AVL Trees 16
AVL trees vs. Hash tables
In an AVL tree, insert/delete/search in O(log n) time worst case,
in a hash table, these operations take O(1) time in practice
AVL Trees 18