0% found this document useful (0 votes)
9 views18 pages

AVL Trees Lect

Data structure

Uploaded by

pramodadudhal303
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views18 pages

AVL Trees Lect

Data structure

Uploaded by

pramodadudhal303
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

AVL Tree

• binary tree
• for every node x, define its balance factor
balance factor of x = height of left subtree of x
– height of right subtree of x
• balance factor of every node x is – 1, 0, or 1
AVL Tree
Balance Factors
0

1 0

0 0 -1
0

0
0 0 0 0

This is an AVL tree.


Balance Factors
Example AVL Tree
10

7 40

45
3 8 30

35 60
1 5 20

25
Example AVL Tree
-1
10

1 1
7 40
0 1 -1
0 45
3 8 30
0
0 0 -1 0 60
35
1 5 20
0
25
put(9)
-1
10

0 1 1
7 40
0 1 -1
0 -1 45
3 8 30
0
0 0 0 -1 0 60
35
1 5 9 20
0
25
put(29)
-1
10

1 1
7 40
0 1 -1
0 45
3 8 30
0
0 0 -2 -1 35
0 60
1 5 20
0 -1
RR imbalance => new node is in 25
right subtree of right subtree of 0

white node (node with bf = –2) 29


put(29)
-1
10

1 1
7 40
0 1 -1
0 45
3 8 30
0
0 0 0 0 60
35
1 5 25
0 0
20 29

RR rotation.
Imbalance Types

• RR … newly inserted node is in the right


subtree of the right subtree of A.
• LL … left subtree of left subtree of A.
• RL… left subtree of right subtree of A.
• LR… right subtree of left subtree of A.
Adjust Imbalance
RL Rotation
n 30 n 30 n 20

10 20 10 30

20 10
LR Rotation
n 10 n 10 n 20

30 10
20 30

20 30
LL Rotation
n 30

temp 20

tl 10 25 tr

temp 20

tl n
10 30

25 tr
RR Rotation

n 10

20 temp

tl 15 25 tr

temp 20

tr
n 10 25

tl 15
Insert Node
Remove An Element
-1
10

1 1
7 40
0 1 -1
0 45
3 8 30
0
0 0 -1 0 60
35
1 5 20
0
25

Remove 8.
Remove An Element
-1
10

2 q 1
7 40
0 1 -1
45
3 30
0
0 0 -1 0 60
35
1 5 20
0
• Let q be parent of deleted node.25
• Retrace path from q towards root.

You might also like