Search code examples
algorithmdata-structuresavl-treetree-rotation

Extra Cases in AVL Trees


AVL Trees seem to have four kinds of transformations: Left-Left, Left-Right, Right-Left, and Right-Right. However, it seems like there could be other circumstances as well. I submit this as Left-Balanced:

enter image description here

Neither Left nor Right rotations can balance this tree. What algorithm would one use to balance it?


Solution

  • Both LL and LR can be applied here

            50
           /  \
         40    55
        /  \
      35    45
      / \   / \
    34  36 44 46
    

    After first LR turn:

               50
              /  \
            45   55
           /  \
         40    46
        /  \
      35    44
      / \
    34  36
    

    After second LR turn:

            45
           /  \
         40    50
        / \    / \
      35  44  46  55
     / \
    34  36
    

    This is the valid AVL tree. Note that

    In an AVL tree, the heights of the two child subtrees of any node differ by at most one

    You can also do the LL turn:

         40
        /  \
      35    50
      / \   / \
    34  36 45  55
           /\
         44  46
    

    Again this is the valid AVL tree.