## Insertion into an AVL Tree

Balance factors are denoted as follows:
balance factor meaning denoted by
+1 R subtree taller +
0 R,L equal height .
-1 L subtree taller -

(Heights of subtrees are indicated in parentheses.)

Let X be the deepest node whose balance factor has become "illegal".  We consider the scenario in which X's balance factor has become too large, +2.  (The scenario that X's balance factor has become too small, -2, can be handled in a symmetric manner.)  This illegal imbalance happened because X previously had a balance factor of +1, and the insertion caused X's right subtree (headed by Y) to increase in height.  This height increase implies that Y had a balance factor of 0, because otherwise either Y would not gain height or Y would become illegally imbalanced.  This scenario is illustrated below and devolves into 2 cases -- the insertion is made into Y's Right subtree or into Y's Left subtree.

```                   X+
/ \
Y
/ \
```

Case 1: insertion into Y's Right subtree

This is cured by a single rotation, resulting in this subtree having the same height as it did before the insertion.

```           X+(h+2)              X++(h+3)                    Y.(h+2)
/ \                  / \          rotate         / \
(h)1  Y.(h+1)        (h)1  Y+(h+2)   (XY)L    (h+1)X.  3(h+1)
/ \      ====>       / \        ====>        / \
2   3                2   3                   1   2
(h) (h)              (h) (h+1)               (h) (h)
^
|
insert
```

Case 2: insertion into Y's Left subtree

There are two possible subtrees of Z where the insertion may take place that are treated similarly.

This is cured by a double rotation, resulting in this subtree having the same height as it did before the insertion.

```           X+(h+2)              X++(h+3)    double          Z.(h+2)
/ \                  / \          rotate         /  \
(h)1  Y.(h+1)        (h)1  Y-(h+2)   (XYZ)L    (h+1)X.  Y+(h+1)
/ \      ====>       / \        ====>       / \    / \
(h)Z.  4(h)        (h+1)Z-  4(h)   same as     1  2   3   4
/ \                  / \          (ZY)R     (h)(h) (h-1)(h)
2   3                2   3         (XZ)L
(h-1) (h-1)            (h) (h-1)
^
|
insert

X+(h+2)              X++(h+3)    double          Z.(h+2)
/ \                  / \          rotate         /  \
(h)1  Y.(h+1)       (h)1   Y-(h+2)   (XYZ)L    (h+1)X-  Y.(h+1)
/ \      ====>       / \        ====>       / \    / \
(h)Z.  4(h)        (h+1)Z+  4(h)   same as     1  2   3   4
/ \                  / \          (ZY)R    (h)(h-1) (h) (h)
2   3                2   3         (XZ)L
(h-1) (h-1)          (h-1) (h)
^
|
insert
```