Skip to content
Advertisement

AVL Tree Implemention In Python

I’m in the middle of turning my Binary Search Tree into an AVL Tree, but i stumbled upon this problem where the balance factor i believe is right but no rotation seems to occur, on the tree itself. If anyone can point out my error, and inaccuracies it would be lovely!

I have made it so that each node gets it’s height from parent_node + 1 when they are made. Balance factor = node.left.height – node.right.height

JavaScript

Advertisement

Answer

Here is a solution:

I changed get_height to get_depth, because the use of height is in checking the difference in depths between the two nodes, so its use in context is wrong.

As such, i added an new recursive function max_depth. that checks all the children of a node, and returns the depth of the node.

I also changed the balancing to a recursive function that keeps going to the parent node, until it reaches the root node.

I added an extra attribute for a treenode which specifies parents node, so that during rotation you can change between x and y.

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