Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More than one rotation needed to balance an AVL Tree?

My best guess is that one rotation is always enough to balance an AVL tree when you insert or delete ONE element from an already balanced AVL tree.

Is one rotation always enough? An example will help where more than one rotations are needed.

PS: I count RL/LR rotations as one rotation only.

like image 350
kBisla Avatar asked Jan 03 '14 20:01

kBisla


People also ask

How many rotations are needed to balance an AVL tree?

Importantly, this means that we never need more than 2 rotations to restore balance an AVL tree after inserting an element. Since rotation is a constant time operation, this means that insertion into an AVL tree is only at worst a constant amount slower than insertion into a BST!

Which rotations are performed to balanced AVL tree?

LR Rotation As LR rotation = RR + LL rotation, hence RR (anticlockwise) on subtree rooted at A is performed first. By doing RR rotation, node A, has become the left subtree of B. Balance factor of each node is now either -1, 0, or 1, i.e. BST is balanced now.

How do you maintain balance in AVL tree?

Balance factor of a node in an AVL tree is the difference between the height of the left subtree and that of the right subtree of that node. The self balancing property of an avl tree is maintained by the balance factor. The value of balance factor should always be -1, 0 or +1.


2 Answers

For insertion I believe one is enough.

but for deletion: consider this tree:

                 50
              /      \
            25       75
           /   \    /   \
          15   40  60    80
               /  /  \    \
              35 55  65   90
                     /
                    62

delete 15 , first the 25's balance factor is destructed, one rotation:

                 50
              /      \
            35       75
           /   \    /   \
          25  40  60    80
                  /  \    \
                 55  65   90
                     /
                    62

but still, we have to check, now the tree's root's balance factor is destructed, have to be rotated again:

                 60
              /      \
            50       75
           /   \     /  \
          35   55   65   80
         /  \       /     \
        25  40     62     90
like image 56
XueYu Avatar answered Sep 19 '22 13:09

XueYu


For insert 1 rotation is at most.
For delete the number of rotation is bounded by O(log(n)). Log(n) is the height of the tree.
More explanation on AVL deletion. When you delete a node from AVL you might cause the tree unbalanced, which you have to trace back to the point where it is unbalanced. If the unbalanced point is the root. You have to rebalance the tree from top to bottom.

like image 38
IanWalker0421 Avatar answered Sep 20 '22 13:09

IanWalker0421