I am trying to insert a new value into an AVL tree. The new insertion causes imbalance (as per the article on Wikipedia, this should belong to the left-right case), hence needs rotation. However, it is not possible to rotate in the current situation, since both children end up in becoming lesser than a parent:
15
/ \
10 27
/ \
8 12
Now if I want to insert 11, the structure becomes imbalanced:
15
/ \
10 27
/ \
8 12
/
11
Since the left subtree is longer, and the left subtree has a longer right subtree, as per the Wikipedia diagrams, this should fall under the Left-Right case. However, there, the element 4 had both left and right subtrees, making the rotation possible. but here, since 12 has only the left subtree, rotation makes it look like:
15
/ \
12 27
/ \
10 8
/
11
resulting in both children of 12 being less than 12. What am I doing wrong here?
You seem to be rotating wrong. The only node with the wrong balance factor is the root, so you rotate around that.
That case involves checking the balance factor of
10(left child of the root): it is -1, so we need two different rotations (left-right case).First, we rotate around 10 to the left, as per the upper left part of this image:
So we get:
Then you continue with the next rotation as described in the image.