0

I have implemented an AVL tree, but I have a problem.

Suppose I have following tree, which of the both solutions for balancing are correct?

Solution 1:

AVL Tree Balancing Solution 1

Solution 2:

AVL Tree Balancing Solution 2

trincot
  • 317,000
  • 35
  • 244
  • 286
BerndHx
  • 1
  • 1

1 Answers1

0

I have implemented an AVL tree

In a correctly implemented AVL, the tree should be kept balanced after every single node insertion or deletion. With that in mind, it is not possible to arrive at an AVL tree that is as imbalanced as the tree you present. It should not be possible that at any time you get a balance factor that is +3. Temporarily, you might have -2 or +2 at the most.

Suppose I have following tree, which of the both solutions for balancing are correct?

This tree is not an AVL tree that just got imbalanced because of a single action, but is a tree that seems to have no AVL history. To turn such a tree into a (balanced) AVL tree it is better to just create a new, complete binary tree (which is balanced by definition) by making an in-order traversal through the tree and build the new AVL tree from scratch.

If we look at this pragmatically, then yes: both of your approaches achieve the goal, but you'd need to define the general procedure you would take for any input tree.

A top down approach -- which you applied in the first solution -- works out well in this example, but in general it may not be the most optimal way to proceed: after balancing the root node, it may be that after having balanced the subtrees, the root is again out of balance and needs to rotate again. Take for example this tree:

               ____7___
              /        \
             6     _____15____
            /     /           \
           5    _11_         _19__
          /    /    \       /     \
         4    9     13     17     21
        /    / \   /  \   /  \   /  \
       3    8  10 12  14 16  18 20  22
      /     
     2     
    /     
   1

...it would be counter productive to rotate the root to the right, since after balancing out the left subtree, it would turn out the new root has to rotate left again, and then again the left subtree needs to be rebalanced.

The second approach -- which aims to first degenerate the tree into a chain -- will work fine, but the number of rotations is high, and can easily lead to more processing time than building the tree from scratch as mentioned above.

trincot
  • 317,000
  • 35
  • 244
  • 286