Professional Documents
Culture Documents
Manmath N. Sahoo
Consider the insertion of following element A,
B, C, , ….,X, Y, Z into the BST
A O(N)
B .
C
.
.
X
Y
Z
Consider the insertion of following element Z,
X, Y, , ….,C, B, A into the BST
Z
X
Y
O(N)
C
B
A
Balanced binary tree
• The disadvantage of a binary search tree is that its
height can be as large as N
• This means that the time needed to perform insertion
and deletion and many other operations can be O(N) in
the worst case
• We want a tree with small height
• A binary tree with N node has height at least O(log N)
• Thus, our goal is to keep the height of a binary search
tree O(log N)
• Such trees are called balanced binary search trees.
Examples are AVL tree, red-black tree.
AVL tree
• An AVL tree is a binary search tree in
which
– for every node in the tree, the height of
the left and right subtrees differ by at
most 1.
(0) A G (1)
D
(0)
Insertion in AVL search Tree
Insertion into an AVL search tree may affect the
BF of a node, resulting the BST unbalanced.
(0) A G (1)
D (0)
E
AVL Search Tree
(-2)
C
(0) A G (2)
D
(-1)
E (0)
Rotation
BL BR x
X
BL BR
(0) 36
(0) 36
BL BR x
BL BR
Unbalanced AVL
search tree after
insertion
RR Rotation
(-2)
(0)
A
RR Rotation B
(-1)
B (0)
AL A c
c h+1 x h+1
x h
BL BR BL BR
AL
Unbalanced AVL
search tree after Balanced AVL
insertion search tree after
Rotation
RR Rotation Example
(-1) (-2)
34 34
(0) (0) Insert 65 (0) (-1)
26 44 26 44
(0) (0) (0) (-1)
40 56 40 56
(0)
65
Unbalanced AVL search
tree
RR Rotation Example
(-2) (-2)
34 44
(0) (-1) RR
(0) (-1)
26 Rotation
44 34 56
(0) (-1) (0) (0) (0)
40 56 26 40 65
(0) 65
(0)
37
B A (+1)
Insert X
h (0) into CR B
C h (-1)
h C
A h-1 c
L
h
CL CR A h-1 c
BR L
x
CL CR BR
Unbalanced AVL
search tree after
insertion
(-2)
RL Rotation
A (+1) (0)
B C (0)
RL Rotation
h (-1) B
C (+1)
A
h c
ALh-1 c
h-1 x
x h h
CL CR BR CR
CL
AL BR
(0) 1
(0)
Insert 14 (+2) 14
64 LR (0)
(0)
(-1) 1
1 64
14 (0)
(0)
Insert 26, 13, 110,98 14
(0)
(-1) (0)
1
64
14
(-1)
(-1)
1 (0)
64
13 (+1)
(0) 110
26
(0)
98
Insert 85
(-1)
(-2)
14 LL 14
(-1) (-1)
(-2) (-1)
1 (0) 64 1 (0) 64
(+2) (0)
13 13
(0) 110 (0) 98
26 26 (0)
(+1) (0) 110
98 85
85 (0)
Deletion in AVL search Tree
Deletion in AVL search tree proceed the same
way as the deletion in binary search tree
Unbalanced AVL
search tree after Balanced AVL
deletion of x search tree after
rotation
R0 Rotation Example
(+1) (+2)
46 46
(0) (-1)
Delete 60 (0) (0)
20 54 20
(+1)
54
(-1) (0) (+1)
18 23 60 18 23
(-1)
BL BR R1 rotation BR
Balanced AVL
search tree after
rotation
R1 Rotation Example
(+1) (+2)
37 37
(+1) (+1)
Delete 39 (+1) (0)
26 41 26
(+1)
41
39 (0) (+1)
18 28 18 28
(0)
(0)
(0) 16
(0) 16
(0) 16
Balanced AVL
search tree after
Rotation
R-1 Rotation Example
(+1) (+2)
44 44
(-1) (-1) Delete 52 (-1) (0)
22 48 22 48
(0) (0)
(0) 52 (0)
18 28 18 28
23 29 23
(0) 29