Skip to content
Advertisement

Rotating the left the subtrees in an AVL Tree in python

A bit of a newbie to computing science.

I have the basics for a binary tree in Python and I was studying some of the applications in an AVL tree:

JavaScript

One of the challenges I’m trying to solve is to rotate the left side of a tree in a function that takes the root as a parameter, but I’m getting the following error:

JavaScript

I tried to solve, but it only prints the root and the right root

Advertisement

Answer

You are rotating the subtree at b, but your function expects the given node to have a right child, which obviously is not the case: there is nothing to rotate at b.

It would have made more sense if your main code would have asked for a rotation at node a:

JavaScript

On the other hand, it would be good to protect your rotate functions a bit. Let it return the root unchanged when it has no right child:

JavaScript

Now your original main code would not trigger an exception, but the tree would also not change — which is indeed the correct behaviour when you call the rotation function on a leaf node (b).

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