I have the following AVL tree:
10
/ \
5 12
/ \ / \
2 8 11 13
/ \ /\
1 4 7 9
If I insert 3 then I get:
10
/ \
5 12
/ \ / \
2 8 11 13
/ \ /\
1 4 7 9
/
3
If I calculate the Balance Factor for each node it seems that every BF is valid:
(Node:BF) -> 10:1, 5:0, 2:-1, 1:0, 4:-1, 8:0, 7:0, 9:0, 3:0, 12:0, 11:0, 13:0
But apparently this tree needs to be rebalanced. Where is there an invalid BF and then how would go about making the necessary rotations.
10 should have a balance factor of 2 with it’s left subtree 5-2-4-3 and its right subtree 12-13. A valid tree after a single rotation might look like 5 | 2 10 | 1 4 8 12 | nil nil 3 nil 7 9 11 13.
A possible method for rebalancing is the cut-link-algorithm:
1. Name the unbalanced node z, one of it’s child y and one of its child’s child x.
2. Rename the nodes to a, b, c in inorder-traversal and let their children be T0, T1, T2 and T3 from left to right.
3. Set b as the new root, a as its left child and c as its right child.
4. Append the four subtrees corresponding from left to right as T0, T1, T2 and T3.