These lecture notes are based on chapter 9 in ``Data Structures, Algorithms, & Software Principles in C'' by Thomas Standish.
Assume we have the following tree.
5
/
3
Then we insert a 2 into the tree.
5
/
3
/
2
Now the tree is the worst case for searching (O(n) rather than O(log n) search).
Should "rebalance" the tree to maintain O(log n) search.
3
/ \
2 5
Can rebalance by an inorder traversal to get sorted order, then
rebuild the tree by choosing the middle value and inserting it.
The inorder traversal in O(n).
So this rebalancing has
Definition: The height of a tree is the length of the longest path in the tree.
Definition: A node in a binary tree has the AVL property if the height of the left and right subtrees differ by at most one.
Definition: If every node in the tree has the AVL property then the tree is said to be an AVL tree.
An AVL tree is shown below.
3
/ \
2 5
The following is not an AVL tree because node 5 does not have the AVL property.
5
/
3
/
2
When AVL property is lost can rebalance via one of four rotations.
A B
/ \ ----------> / \
B T3 T1 A
/ \ / \
T1 T2 T2 T3
A B
/ \ ----------> / \
T1 B A T3
/ \ / \
T2 T3 T1 T2
C B
/ \ ----------> / \
A T4 A C
/ \ / \ / \
T1 B T1 T2 T3 T4
/ \
T2 T3
A B
/ \ ----------> / \
T1 C A C
/ \ / \ / \
B T4 T1 T2 T3 T4
/ \
T2 T3
AVL-tree node structure
typedef enum {LeftHeavy, Balanced, RightHeavy} BalanceFactorType;
typedef struct AVLTreeNodeTag {
BalanceFactorType balance_factor;
KeyType key;
struct AVLTreeNodeTag *left;
struct AVLTreeNodeTag *right;
} AVLTreeNode;
local balance factor adjustments only during rebalancing
.
.
.
/
3
/
2
.
.
.
/
3
/
2
/
1
.
.
.
/
2
/ \
1 3
Analysis