Académique Documents
Professionnel Documents
Culture Documents
v
6 3 4 8
AVL Trees
4 44 2 17 1 32 1 48 62 2 50 1 88 78 1 3
An example of an AVL tree where the heights are shown next to the nodes:
AVL Trees 2
n(2)
3 4 n(1)
Fact: 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. We easily see that n(1) = 1 and n(2) = 2 For n > 2, an AVL tree of height h contains the root node, one AVL subtree of height n-1 and another of height n-2. That is, n(h) = 1 + n(h-1) + n(h-2) Knowing n(h-1) > n(h-2), we get n(h) > 2n(h-2). So
n(h) > 2n(h-2), n(h) > 4n(h-4), n(h) > 8n(n-6), (by induction), n(h) > 2in(h-2i)
Solving the base case we get: n(h) > 2 h/2-1 Taking logarithms: h < 2log n(h) +2 Thus the height of an AVL tree is O(log n)
2004 Goodrich, Tamassia AVL Trees
b=x
before insertion
2004 Goodrich, Tamassia AVL Trees
after insertion
4
Trinode Restructuring
let (a,b,c) be an inorder listing of x, y, z perform the rotations needed to make b the topmost node of the three
a = z T
0
a = z
c = y b = x T
3
case 2: double rotation (a right rotation about c, then a left rotation about a)
T
1
T
2
b = y a = z T
0
T c = x
1
T
2
b = x a = z T
0
c = y T
1
T
1
T
2
T
3
T
2
T
3
AVL Trees
64
78
2y
50 2
7
1 88
4
62
x
5
3
54
unbalanced...
T3 T2
4 3 17 1 32 1
T0
T1
2
44
4
62
x z6
5
78 2
2 y 2 1
48 50
3
54
...balanced
7
88
T2
2004 Goodrich, Tamassia AVL Trees
T0
T1
T3
b=y c=z
T2 T1
T1
T0
7
b=x c=y T2
T3
T0
T1
T3
b=x c=z
T3
T1
T0
before deletion of 32
2004 Goodrich, Tamassia AVL Trees
after deletion
9
b=y
c=x
using a linked-structure binary tree height of tree is O(log n), no restructures needed initial find is O(log n) Restructuring up the tree, maintaining heights is O(log n) initial find is O(log n) Restructuring up the tree, maintaining heights is O(log n)
find is O(log n)
insert is O(log n)
remove is O(log n)
AVL Trees
11