13 Rotations Avl Trees
13 Rotations Avl Trees
Chris Kauffman
Week 12-2
Practice/Demo Sites
I jGrasp is so-so for seeing tree operations
I Play with Blanced Binary Search Trees online using the
following applets (titles hyperlinked)
I A self-balancing tree
I Operations
I Proof of logarithmic height
AVL Balance Property
T is an AVL tree if and only if
I T.left and T.right differ in height by at most 1
I AND T.left and T.right are AVL trees
1 2 3 4
5 6 7 8
Answers
T is an AVL tree if and only if
I T.left and T.right differ in height by at most 1
I AND T.left and T.right are AVL trees
Left 2, Right 0
Left 0, Right 1
Left 2, Right 4
80 not AVL 95 not AVL
Nodes and Balancing in AVL Trees
Problem 1 Problem 2
I 40 was just inserted I 85 is being removed
I Rebalance tree rooted at 16 I Rebalance tree rooted at 57
I Left-rotate 16 I Right rotate 57
Question: Can this be fixed with single rotation?
Left-Right Right-Left
I Left Rotate at k1 I Right Rotate at k3
I Right-rotate at k3 I Left Rotate at k2
Fixing an Insertion with a Double Rotation
Insert 5, perform two rotations to balance heights
I Problem is at 8: left height 3, right height 1
I Left rotate 4 (height imbalance remains)
I Right rotate 8 (height imbalance fixed)
Double Rotation Practice
I Inserted 51
I Which node is unbalanced?
I Which rotation(s) required to fix?
Rebalancing Answer
class Node<T>{
Node<T> left, right;
T data;
int height;
}
I T has height H
I Assume for height h < H,
smallest size of T is
Sh = Fh+2 − 1
I Suppose Left is 1 higher SH = size(Left) + size(Right) + 1
than Right
= (FH+1 − 1) + (FH − 1) + 1
I Left Height: h = H − 1
= FH+1 + FH − 1
I Left Size:
F(H−1)+2 − 1 = FH+1 − 1 = FH+2 − 1
I Right Height: h = H − 2
I Right Size:
F(H−2)+2 − 1 = FH − 1
Fibonacci Growth
I Exponentially:
4000
●
FH ≈ φH = 1.618H
size
●
I φ: The Golden Ratio
2000
●
● I So, log(FH ) ≈ H log(φ)
● ●
● ● ● ● ● ● ● ● ● ● ● ●
0