Close, but not quite. You’re rotating funny.
A and C look fine, no rotations are needed for those.
In B, you would add C to the left of D. First thing you get is… let’s see if I can get this…
M
/ \
E P
/ \ / \
A H O X
\ /
D W
/
C
So you start checking. C has no siblings, so you move up. D has no siblings, so you move up. A has a sibling, H. A is height 2, H is height 0. Uh-oh! You need to rotate!
Now, I’m basically copying thing out of my textbook (Goodrich & Tamassia), because rotate operations are annoying and I want to make sure I do it right.
Anyway, E is the first unbalanced node we find, because one of its children is height 2 and one is height 0. Now, we find its taller child. That’s A. Finally, we find A’s taller child. That’s D, since it’s A’s only child.
To rebalance the tree, we take E, A and D and put them in increasing order: A, D, E. The middle one of those three is D, so D needs to be at the top, with A and E as its left and right children, respectively.
M
/ \
D P
/ \ / \
A E O X
/
W
C H
Now we take C and H (and all of their children, if they had any) and attach them back to the tree, on A and E.
So now we have
M
/ \
D P
/ \ / \
A E O X
\ \ /
C H W
We continue our checking up the tree, and huzzah, everything’s balanced!
Let me know if you understand how this works, and see if you can figure out the last part of the problem on your own. (I know how hard AVL trees can be, so I’ve been nice, but I’m not going to give step-by-step answers after this one.)