Академический Документы
Профессиональный Документы
Культура Документы
Balancing Trees
Many algorithms exist for keeping trees balanced
Adelson-Velskii and Landis (AVL) trees
Splay trees and other self-adjusting trees
B-trees and other multiway search trees (for
very large trees)
Structural properties
1. Binary tree property
(0,1, or 2 children)
2. Heights of left and right
subtrees of every node
differ by at most 1
Result:
Worst case depth of any
node is: O(log n)
11
6
4
10
7
12
13
14
15
5
Note: height(null) = -1
A0
A1
A2
A3
A4
11
12
10
6
4
1
8
5
11
3
2
7
a+b a
= =
a
b
The golden
section:
1+ 5
1.62
2
1+ 5
=
Note: =
10
Induction step:
11
12
10
5
An AVL Tree
10
1. Track Balance
15
2. Detect Imbalance
2
10
20
3. Restore Balance
20
1
height
children
data
15
30
What if we insert(30)?
13
14
AVL find:
h+1
AVL insert:
h+2
a
b
X
15
h
h
Y
16
h+3
15
4
3
Single rotation
X<b<Y<a<Z
22
24
19
10
17
20
16
15
b
h
h+1
3
Height of tree before/after? Effect on Ancestors? Cost?
17
h+1
h
18
h+2
a
h+2
Single rotation
b
Z
X
h+1
X<b<Y<a<Z
a
h
h+3
h
10
a
h+1
Y
19
Z
20
h+1
h-1
c
U
a
c
15
17
22
16
20
24
5
15
19
a
h-1
10
3
Second rotation
19
h-1
22
h+3
h
h-1
21
a
c
First rotation
h-1
h-1
h+2
h+1
X<b<U<c<V<a<Z
V
Insert on left childs right (at U or V)
h-1
h+3
h+2
h+2
10
V
17
16
23
22
20
24
24
15
19
8
6
17
10
4
3
h+2
20
h+1
22
16
24
h-1
5
Double rotation
15
h+2
19
h+1
17
16
22
20
24
25
a
h
h+1
Single rotation
h+2
h+1
h
h-1
h+1
26
b
h+1
a
h
h+2
Z
27
28
Insertion procedure
1.
2.
3.
4.
1. single rotation?
5
2
2. double rotation?
11
13
Single Rotation
4
15
0
10
10
Insert(33)
20
17
30
15
9
12
20
17
10
12
30
30
Unbalanced?
33
How to fix?
31
32
10
Insert(18)
1
15
10
12
0
Unbalanced?
20
1
30
12
17
15
20
10
17
30
0
How to fix?
18
33
34
10
10
15
12
20
1
15
12
10
15
17
10
12
17
30
20
18
18
35
30
36
10
17
15
Unbalanced?
12
20
0
18 30
How to fix?
37
AVL complexity
What is the worst case complexity of an insert?
39
38