If I remember my data structures homework correctly:
What you do is store the balance factor in the node itself as an int that's either:
- -1: the node's left subtree is a level higher than the right one (left-heavy)
- 0 the node is balanced; or
- 1 the right subtree is higher (right-heavy).
You insert(Node subtree) function returns a boolean, which is true if the insertion made the height of subtree increased. You update the balance factor and rebalance the tree as you return from the recursive insert() calls.
This is probably best explained with a few examples:
If the current node is at balance factor -1, you're inserting into the right subtree, and insert(rchild) returns true, you:
- update the balance factor of the current node to 0 - the left subtree was higher before the insertion, and the right subtree's height increased, so they're the same height now; and
- return false - the shallower tree's height increased, so the current node's height stays the same
If you're inserting into either subtree, and insert(…) returns false:
- the balance factor of the current node is unchanged - the subtree heights are the same as before, and so is the balance
- return false - the subtree heights haven't changed, so neither has the current node height
If the current node's balance factor is 0, you're inserting into the left subtree, and insert(lchild) returns true:
- the balance factor changes to -1 - the subtrees were the same height before the insertion, and the insertion made the left one higher
- return true
(Analogously, if inserting into the right subtree, the balance factor will change to 1.)
If the current node's balance factor is -1, you're inserting into the left subtree, and insert(lchild) returns true:
The balance factor would change to -2, which means you have to rebalance the node by doing the appropriate rotation. I'll admit I'm drawing a blank at what each of the four rotations will do to the balance factor and what insert(current) will return, hopefully the previous examples explain the approach to tracking the nodes' balance sufficiently.