Professional Documents
Culture Documents
AVLTrees
AVLTrees
v
6 3 4 8
44 2 17 1 32
4 3 1
78 2 50 1 48 62 1
88
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)
48
62
48
62
b=x
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)
AVL Trees 3
54
before insertion
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 b=y T0 c=x T1 T2 T3 a=z c=x b=y T1 T2 a=z c=y
64
78
2 y
50 1 2
7
1 88
1
48
4
62
x
5
a=z c=y
case 2: double rotation (a right rotation about c, then a left rotation about a)
3
54
unbalanced...
T3 T2
4 3 17 32 1
T0
b=x T3 b=x
T1
2
44
4 x
62
1 1
48
2 y 2
50
z6
5
78
3
54
...balanced
T3
7
88
T2
T0 T1 T2 T3 T0 T1 T2 5 AVL Trees AVL Trees
T0
T1
T3
b=x
c=y T2
T0 T1
T2
T2
T3
T0
T1
T3
c=z
c=z b=y a=x T0 T2 T3 T3
AVL Trees
b=x c=z T2
single rotation
a=y b=x T3 T2 T0 T1
AVL Trees
T3
T1
T0
8
T1
T2
T1
T0
7
32
50
78
50
78
w 88
17
48
54
88
48
54
50
78
c=x
50
88
before deletion of 32
AVL Trees
after deletion
9
48
54
88 AVL Trees
48
54
10
find is O(log n)
height of tree is O(log n), no restructures needed
insert is O(log n)
initial find is O(log n) Restructuring up the tree, maintaining heights is O(log n)
remove is O(log n)
initial find is O(log n) Restructuring up the tree, maintaining heights is O(log n)
AVL Trees
11