0% found this document useful (0 votes)
15 views47 pages

Handout 6 Avl Trees

The document discusses AVL trees, a type of self-balancing binary search tree that maintains a height of O(log N) through specific rotations during insertions and deletions. It explains the concept of balance factors, the methods for inserting and deleting nodes, and the necessary rotations to maintain balance. Additionally, it provides examples and code snippets for implementing AVL tree operations.

Uploaded by

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

Handout 6 Avl Trees

The document discusses AVL trees, a type of self-balancing binary search tree that maintains a height of O(log N) through specific rotations during insertions and deletions. It explains the concept of balance factors, the methods for inserting and deleting nodes, and the necessary rotations to maintain balance. Additionally, it provides examples and code snippets for implementing AVL tree operations.

Uploaded by

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

AVL Trees

Zareen Alamgir

Material taken mainly from


Mark Alan Weiss Book Chapter 4 (section 4.1 - 4.4)
1
Trees and balance
BST operations A binary tree
We want a tree with N node has
are closely
with small height at least
related to
height
height. (log N)

Our goal is to keep the height of a root


BST O(log N) 9

Some tree collections balance themselves 6 14


as new nodes are added.
Balanced binary search trees. 4 8 19
AVL tree, red-black tree
height = 3 7
(balanced)
2
Calculating Tree height
• Height is max number of nodes in path from root to any leaf.
 height(leaf) = ?
 height(A) = ?

A
 Hint: it's recursive!

A.left A.right
 height(leaf) = 0
 height(A) = 1 + max(
height(A.left), height(A.right))

3
AVL trees

AVL • a binary search tree that uses


modified add and remove operations
to stay balanced as its elements
Tree change

A-V & L
Invented in 1962 proved that an AVL
(Adelson-
by two Russian tree's
VelskiiandLandis)
mathematicians height is always
O(logN).

4
AVL trees
• Basic idea
 If the tree becomes unbalanced after insert or delete
operation, repair the tree until balance is restored.
 Rebalancing operations are relatively efficient O(1)
 Overall tree maintains a balanced O(log N) height
 Fast to add/search

5
Balance Factor - BF
• Balance factor (BF) for a tree node T
 BF = height of T’s right subtree - height of T’s left subtree.
 BF(T) = Height(T.right) - Height(T.left) -2

AVL tree maintains a "balance 3 1


factor"
in each node of 0, 1, or -1
• no node's two child subtrees differ in height -2 0
by more than 1

It can be proven that the height of an -1


AVL tree withNnodes is O(logN)
Node shows BF
0

6
Is this an AVL tree ?
Each Node shows node value

AVL tree not an AVL tree

7
Tracking subtree height
• Many of the AVL tree operations depend on height.
 Height can be computed recursively by walking the tree; too slow.
 Instead, each node can keep track of its subtree height as a field:

class AVLNode {
private: 10 data
int data;
int height; 3 3 height
AVLNode * left; 10
AVLNode * right; left/
}
2 1 right
5 20

0 1 0 0
2 9 15 30

0
7
8
AVLTree Insert
• For all AVL operations, the tree is balanced before the operation began.
• Adding a new node
 Just like BST, traversing left and right to find the proper location and insert the
new node.
 But adding this new node may unbalance the tree by 1

AVL.add(49) 55

29 87

13 42

49
9
AVL Insert

Which nodes in AVL tree has become unbalanced


due to insert?

10 10
Consider the lowest
Add 3 node that has
2 15 2 5 become unbalanced,
and call it X

7 7

10
AVL Add cases
Balanced x x
AVL tree y y Symmetric Case
Balance AVL Tree
h h
h h

A new node is inserted, the lowest node that becomes unbalanced is x.


There are four possibilities
x x x x

y y y y

h+1 h+1 h+1 h+1

A B B C

1) Left-Left 2) Left-Right 3) Right-Left 4) Right-Right


11
Key idea: rotations
• If a node has gone out of balanced in one direction
 Rotate it in the opposite direction.
• What is Rotation ?
 Technically its a swap between parent and left or right child,
maintaining proper BST ordering.

25 8

rotate right
8 3 25

3
12
Right rotation (clockwise): (Fix Case1(LL))

 left child y becomes parent


 original parent x demoted to right
 y's original right subtree B (if any) is attached
to x as left subtree
Right
Rotation x y

y x

13
Right rotation steps
1. Detach left child (11)'s right subtree (27) (don't lose it!)
2. Consider left child (11) be the new parent.
3. Attach old parent (43) onto right of new parent (11).
4. Attach new parent (11)'s old right subtree (27)
as left subtree of old parent (43).

43 X 43 11
Y
11 65 11
65
8 43
8 27 8 27
3 27 65
3 3

14
Right rotation code
void AVLTree:: rightRotate(AVLNode *& x) {
// 1. detach Y(left child’s) right subtree
AVLNode * orphan = x->left->right;

// 2. consider Y(left child) to be the new parent


AVLNode * y = x->left;

// 3. attach old parent onto right of new parent


y1->right = x;

// 4. attach new parent's old right subtree as


// left subtree of old parent
x->left = orphan;

x->height = height(x); // update nodes'


y->height = height(y); // height values
x y
x=Y;
} y x

15
Right rotation example
• Insert node with value=1
• Which nodes have become unbalanced?

Which will be X ?

What is the balance factor


of X before rotation?
1

16
Right rotation example
• What is the balance factor of X before rotation
• What is the balance factor of X after rotating?

x
x

y y

17
Left rotation
• left rotation (counter-clockwise): (fixes Case 4 (RR))
 right child y becomes parent
 original parent X demoted to left
 y's original left subtree B (if any) is attached to X as left subtree

x y

y x

18
Left rotation code
void AVLTree::leftRotate(AVLNode * & X) {

LEFT AS EXERCISE

19
Left Right Case
• A single right rotation Problem Case
X Y

Y X

C A

A C

Does not fix CaseB2 (LR). B


Similarly, a single left rotation does not fix Case 3 (RL).)

20
Left-right double rotation
• left-right double rotation: (fixes Case 2 (LR))
 1) left-rotate Y ... reduces Case 2 into Case 1
 2) right-rotate X to fix Case 1

X X Z

Y Z Y X

Z Y

21
Left-right rotation example
• What is the balance factor of Y, X, Z before and after rotating?

x
8

y
4
z
6

22
Left-right rotation example
• What is the balance factor of Y, X, Z before and after rotating?

x z
8 6

y y x
4 4 8

z
6

23
Right-left double rotation
• right-left double rotation: (fixes Case 3 (RL))
 1) right-rotate Y ... reduces Case 3 into Case 4
 2) left-rotate X to fix Case 4

24
Right-left double rotation
• right-left double rotation: (fixes Case 3 (RL))
 1) right-rotate Y ... reduces Case 3 into Case 4
 2) left-rotate X to fix Case 4

X Z

Y X Y

25
AVL Example 1
Numbers outside the
3 node shows Height
20 of the node
1 2
10 30
0 0
5 25 40 1
0 0
35 45

Now Insert 34

26
AVL Example 1
Numbers outside the
3 node shows Height
of the node
20
1 3
10 30
0 0 2
5 Imbalance 25 40

1 35 45
Insertion of 34 0
34

27
AVL Example 1
Numbers outside the
3 node shows Height
of the node
20
1 3
10 30
0 0 2
5 Imbalance 25 40

1 35 45
Insertion of 34 0
34

28
AVL Example 1
Insertion of 34 Numbers outside the
3 node shows Height
of the node
20
1 3
10 30
0 0
5 Imbalance 25 35

34 40

45

29
AVL Example 1
Numbers outside the
3 node shows Height
20 of the node
1 2
10 35
0 1
5 30 40 1
0
0 25 34 45

30
AVL Example 2

Insert 3 Insert 2 Insert 1 Single Right Rotation

3 3
3 2

2 2
1 3

31
An Example
Insert 4
2

1 3

Insert 5
2
Single Left Rotation 2
1 3
1 4
4
3 5
5
32
An Example

Insert 6

2 4
Single Left Rotation
1 4 2 5

3 5 3 6
1

33
An Extended Example

Insert 7
4

Single rotation 4
2 5

3 6 2 6
1

7
1 3 5 7

34
4
Insert 16 then 15
4 Double RL Rotation 2 6

2 6 1 3 5 7 X

15 Z
1 3 5 7 X
16
16 Y Y
4
15 Z
2 6

1 3 5 15

7 16
35
4
Insert 14
2 6
4
Double rotation
1 3 5 7
2 6 X
15

1 3 5 15
Y
14 16
16
Z 7
4

14
2 7

1 3 6 15

5 14 16
36
DoubleRotation
void AVLTree::doubleLeftRightRotation(AvlNode*&X)
{
leftRotate ( X->left );
rightRotate( X );
}

void AVLTree::doubleRightLeftRotation(AvlNode*&X)
{
Left as EXERCISE
}

37
AVL INSERT
• First, insert the new key as a new leaf just as in
ordinary binary search tree
• Then trace the path from the new leaf towards the
root.
• For each node p encountered, check if heights of
left(p) and right(p) differ by at most 1.
 If yes, proceed to parent(p).
 If not, restructure by doing either a single rotation or a
double rotation

For insertion, once we perform a rotation at a node x, we


won’t need to perform any rotation at any ancestor of x.

38
AVL INSERT
void insert(AvlNode * & t, int x) {
if (t == nullptr)
t = new AvlNode{ x, nullptr, nullptr
};
else if (x < t->element)
insert(x, t->left);
else if (t->element < x)
insert(x, t->right);

balance(t);
}

39
AVL BALANCE
void balance(AvlNode * & t)
{
if (t == nullptr)
return;

if (height(t->left) - height(t->right) > ALLOWED_IMBALANCE)


if (height(t->left->left) >= height(t->left->right))
?????? Which Rotation
else
?????? Which Rotation
else if (height(t->right) - height(t->left) >
ALLOWED_IMBALANCE)
if (height(t->right->right) >= height(t->right->left))
?????? Which Rotation
else
?????? Which Rotation

t->height = max(height(t->left), height(t->right)) + 1;


}
40
AVL DELETION

41
AVL DELETION
• Deletion may be more time-consuming than
insertion.
• First, we apply DeleteByCopying to delete a
node as in BST
 This reduce the problem of deleting a node with two
children to deleting a node with at most one child.

• After a node has been deleted from the tree


 Trace the path from the deleted node towards the root.
 For each node p encountered, check the balance factor.

• If balanced, proceed to parent(p).


• If not, perform an appropriate rotation at p.
42
AVL DELETION
• The rebalancing does not stop in DELETION
after the first node X with balance factor ±2
is balanced as is the case with Insertion.

• The deletion leads to at most O (lg n)


rotations
 because in the worst case, every node on the path
from the deleted node to the root may require
rebalancing.

43
When a node is deleted in
AVL Delete Cases subtree A, x becomes
unbalanced.

x Case:1 BF=+2
x
y BF=0
y y BF=+1 x BF=0
h h-1
h-1 h
h h-1
A h h-1
A
Single
A
C C Rotation C

Balanced AVL tree


Balanced Tree Deletion in A
BF=+2 y BF=-1
x Case:2 x
BF=0 x BF=+1
y y
h
h h-1
A h
A h-1
h h h h
Single A C
Rotation B

Balanced Tree Balanced AVL tree


44
AVL Delete Cases

x x

y y

h h-1

h h-1 A h h-1
A

B B

After Deletion
Zig-Zag imbalance
Case:3

45
AVL Delete Cases
BF=+1 BF=+2 Z
BF=0
x x
BF=-1 BF=-1 BF=+1
y y x BF=0 y
BF=-1
BF=-1
h Z Z
h-1
h-1 h-1 C
A A h-1
A B D
C
C
h-2
h-1 h-2
h-1
After Double Rotation
After Deletion
Balanced AVL-Tree
Zig-Zag imbalance
Case:3 Expanded

46
AVL Delete Cases
There are three cases in Deletion
And
three Symmetric cases
(Left as exercise)

NOTE:
Two Single Rotation cases we discussed for
deletion are same no need to distinguish
them when performing rotation

• Deletion of a node may not need an immediate


rotation
 It may improve the balance factor of its parent (from ±1 to
0),
 but it may also worsen the balance factor for the
48

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy