Reputation: 2881
I am trying to implement an AVL tree and I'm having a hard time knowing when I need a RR or RL rotation (same for LL and LR).
What are the preconditions for each and how are they different. I know when I see a picture of the tree (intuitively) but what are the actual conditions ?
This is a logic problem, no code necessary, thank you.
What I do know is it involves the tree being left heavy or right heavy. But how do you determine that ?
Upvotes: 1
Views: 523
Reputation: 176
There may be different solutions, but one is as following:
When adding an item recursively, at each recursive call you should keep track of whether that call added the node to the left or right subtree (by letting the add function return it, for example). After the recursive call you check the height invariant. If you find that the it has been violated at that node after the insertion, you will then know the path to the imbalance.
Some (incomplete) pseudo-code:
add(item, node):
if item < node.value //should add to left subtree
if node.left is empty
//add item here
else
addedLeft := add(item, node.left)
if node.left.height - node.right.height > 1
if addedLeft
//you know the path to the subtree causing the imbalance is LL, do a RR (single-right) rotation
else
//path is LR, do a LR (double-right) rotation
...
The recursive calls will unfold bottom-up from the added node and the general idea is to check at which node the invariant is violated (if any). When that node is discovered, you need to know the path to the subtree causing the imbalance. One must solve that problem somehow, this is one solution.
Upvotes: 1