AVL Tree Example
CS 402 Advanced Tree Examples
Here is an example of insertion into an AVL tree.
In each figure, we give the balance factor for each node
in red, and its data value in black.
Starting with an empty tree, we insert the keys
14, 71, 3, 52, 68, 92, 59, 37, 22, 49 and 41.
The sequence begins here, or
you may use the index below.
The steps for inserting into an AVL tree are these:
- Insert the key as you would in an ordinary BST.
The new node will have
The path you take as you move from the root looking for
the place to insert the node
is the insertion path.
As you search down the tree, remember the location of the
last node which has a balance factor ±1. Call this node A. It is the node
on the insertion path closest to the insertion point
having a non-zero balance factor.
- Adjust each balance factor of each node
along the search path from below A to
the new node, excluding the endpoints. Each will be initially zero.
If you move left when leaving the node, set its factor to +1. If you
move right, set to -1. If there is no A node, adjust the
factors for all the nodes
on the search path starting with the root
up to the new node, and omit the remaining steps.
- Adjust the the balance factor of A. If you move right to the insertion,
subtract one, if you move left, add one. This will leave A's factor at
-2, 0, or +2. If it is 0, the insertion is complete.
- If A has factor ±2, perform the appropriate rotation on
the subtree rooted at A. The rotation specifies new
balance factors for the A, B, and C nodes. No other balance factors
are changed by the rotation.
Beginning with the empty tree, we present the tree after each
of these steps:
After Inserting 14
After Inserting 71
After Inserting 3
After Inserting 52
After Inserting 68
After Inserting 92
After Inserting 59
After Inserting 37
After Inserting 22
After Inserting 49
After Inserting 41