Daniel Kane: Data Structures
Daniel Kane: Data Structures
Daniel Kane: Data Structures
AVL Tree
Implementation
Daniel Kane
Department of Computer Science and Engineering
University of California, San Diego
Data Structures
http://bit.ly/algospecialization
Learning Objectives
Implement AVL trees.
Understand the cases required for
rebalancing algorithms.
Outline
1 AVL Trees
2 Insert
3 Delete
AVL Trees
Need ensure that children have nearly the
same height.
Problem
Updates to the tree can destroy this property.
Problem
Updates to the tree can destroy this property.
1 AVL Trees
2 Insert
3 Delete
Insertion
AVLInsert(k, R)
Insert(k, R)
N ← Find(k, R)
Rebalance(N)
Rebalancing
If
|N.Left.Height − N.Right.Height| ≤ 1
ne.
Problem
Diculty if heights dier by more.
Problem
Diculty if heights dier by more.
N.Height ← 1+ max(
N.Left.Height,
N.Right.Height)
Rebalancing
If left subtree too heavy, rotate right:
Bad Case
Doesn't work in this case.
Fix
Must rotate left rst.
Rebalance
RebalanceRight(N)
M ← N.Left
if M.Right.Height > M.Left.Height:
RotateLeft(M)
RotateRight(N)
AdjustHeight on affected nodes
Outline
1 AVL Trees
2 Insert
3 Delete
Delete
Deletions can also change balance.
New Delete
AVLDelete(N)
Delete(N)
M ← Parent of node replacing N
Rebalance(M)
Conclusion
Summary
AVL trees can implement all of the basic
operations in O(log(n)) time per operation.