2. AVL Trees
• AVL tree is a Balanced Binary Search Tree
• Balanced Factor : Balanced Factor of a
node is the absolute difference in heights
between left and right sub trees
• AVL tree is defined is a Binary Search
Tree tree such that, for each node,
balanced factor ≤ 1
3. AVL-Trees
An AVL-tree is a BST with the property that at
every node the difference in the depth of the
left and right subtree is at most 1.(0,1,-1)
OK
not OK
Two binary search trees: (a) an AVL tree; (b) not an AVL tree (unbalanced
nodes are darkened)
4. AVL Tree
Insertion/Deletion in an AVL-tree is more
complicated: Inserting/Deleting a new element may
break the balance of the tree.
But we can't just place the new element somewhere
else, we have to maintain the BST property.
Solution: insert in standard place, but then
rebalance the tree using the operation “ROTATION”.
Thus, many operations (searching, insertion, deletion) on
an AVL tree will take O(log N) time.
5. Rotations
• When the tree structure changes (e.g., insertion or
deletion), we need to transform the tree to restore the
AVL tree property.
• This is done using :single rotations or double rotations.
x
y
A
B
C
y
x
A
B C
Before Rotation After Rotation
e.g. Single Rotation
6. Single rotation: Right Rotation
The new key is inserted in the subtree A.
The AVL-property is violated at x
height of left(x) is h+2
height of right(x) is h.
7. Single rotation: Left Rotation
The new key is inserted in the subtree C.
The AVL-property is violated at x.
14. Double rotation : Left Right
Rotation
The new key is inserted in the subtree B1 or B2.
The AVL-property is violated at x.
x-y-z forms a zig-zag shape
also called left-right rotate
15. Double rotation- Right Left
Rotation
The new key is inserted in the subtree B1 or B2.
The AVL-property is violated at x.
also called right-left rotate
16. So?
Rotation does not change the flattening, so we still
have a BST.
But the depth of the leaves change by -1 in A, stay
the same in B, and change by +1 in C.