AVL specific case balancing

34 Views Asked by At

I have been revisiting old basic algorithms for a class I an online course I am about to watch after christmass. It had been a generally light read, until I reached AVLs. Back when I was learning them, I do not remember having any problem, but after a little more than 10 years, I am no longer as good. While I solve most cases easily, I have stuck for more than 5 hrs on this example:

    51
   /  \
  19   55
 / \    \
10  37   61
    / \  
   28 46

Inserting 40 into the tree, left child of 46, requires a Single Left Rotation to fix the balance...why? Isn't 40 inserted into the left side of the Right child of 19, who becomes unbalanced? Why is it not a double rotation? What do I fail to see?

2

There are 2 best solutions below

1
On

Here is how it goes:
1. After insertion:

    51
   /  \
  19   55
 / \    \
10  37   61
    / \  
   28 46
      /
     40

It is clear that 19 node becomes unbalanced.
2. That's why it is rotated left once. So it becomes:

     51
    /  \
   37   55
   / \   \
  19  46  61
 / \   /    
10 28 40 

Now the tree is balanced again.

0
On

And funnily enough, trying to explain my problem revealed what I was doing wrong. The tree is left heavy and tree's left subtree is NOT right heavy, so it's a single rotation.