Professional Documents
Culture Documents
4
5
3
Is this balanced?
2
1 3 5
6
7
AVL Trees
6
7
2
Perfect Balance
Want a complete tree after every operation
tree is full except possibly in the lower right
This is expensive
For example, insert 2 in the tree on the left and then rebuild as a complete tree
6 5
4
1 5 8
2
4 6
8
9
3
1
AVL Trees
Node Heights
Tree A (AVL) height=2 BF=1-0=1 Tree B (AVL) 2
6
1 0 1
6
1
4
0 0
9
0
4
0 0
9 5 8
6
1 1 1
6 4
0 0 1
4
0 0 0
9 5
9
-1
5
0
6
1 2 1
6
1
4
0 0 1
9
0
4
0
8
0
0
5
0
8 7
AVL Trees
j
h h
k
h
Z
10
Y
AVL Trees
j k
h+1 h h
Y
X
AVL Trees 11
j k
h+1 h
Do a right rotation
Y
X
AVL Trees 12
j k
h+1 h
Do a right rotation
Y
X
AVL Trees 13
k
h+1
h
j
h
Y
AVL Trees
Z
14
j
h h
k
h
Z
15
Y
AVL Trees
j
k
h+1
Y
AVL Trees 16
k
h
j
h+1
X Y
Z
AVL Trees 17
j
h h+1
k
h
Y
AVL Trees 18
j
h
k
h
X
V
h+1
h or h-1
W
AVL Trees 19
j k i V
W
AVL Trees 20
j i k W X V
AVL Trees
21
j i k W X V
AVL Trees
22
i k
h h or h-1
j
h
W
AVL Trees
Z
23
Implementation
balance (1,0,-1) key left right
No need to keep the height; just the difference in height, i.e. the balance factor; this has to be modified on the path of insertion even if you dont perform rotations Once you have performed a rotation (single or double) you wont need to go back up the tree
AVL Trees 24
20
0 1
Insert 5, 40 0
10
0
30 25 35
AVL Trees
27
20
1 1 1
20 30
0
10
0
0
30
0
10
0
25
35
5
Now Insert 45
25
35
0
40
AVL Trees
28
20
1 2 1
20 30
0
10
0
0
30
2
10
0
25
Imbalance
35
1 40 0 45
AVL Trees
25
0
40 1
0
35
Now Insert 34
29
45
20
1 3 1
20 35
1 0 25
10
0
0 Imbalance 25
30
2
10
0
40
1 35
5 45 0
30 34
40 1
0
45
Insertion of 34 0
34
AVL Trees 30
AVL Trees
31
AVL Trees
32