Skip to content
Advertisement

How to implement AVL tree rotation?

I have coded an AVL Tree and my logic for the rotations is correct but I am still not able to get it working properly. For rotations on the root node my rotations work properly but if the rotation is further down the tree, the parent node does not point to the new node that has been rotated into place and continues to point to the node that was in place before the rotation. I am pretty sure the issues lies with my insert method but I am not sure how to get the parent node to point to the new node when a rotation occurs. I know you can add a parent variable to fix this but I am wondering if there is a way to do it without that.

JavaScript
JavaScript
JavaScript

Advertisement

Answer

In your code, the insert method returns the new root of the subtree, after the insertion has been done and any needed rotations have happened. Your issue is that you’re not using that return value when you recursively call insert on one of your child nodes.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement