data-structuresavl-tree

Number of balance operations in an AVL Tree when a sequence of decreasing numbers is inserted


How many balance operations will there be when inserting n numbers (decreasing from n down to 1) into an empty AVL tree?

Example:

AVL tree        number of rotations
--------------- -------------------
8                     0

  8
┌─┘                   0
7                    

    8       7              
  ┌─┘     ┌─┴─┐       1
  7   →   6   8
┌─┘
6

...etc

I know the answer is ~(n-logn), but how to prove this with induction?


Solution

  • Here are some invariants (to be proved) when we have an AVL tree with 𝑛 nodes (𝑛 > 0) that was constructed by adding a sequence of decreasing values:

    1. All right subtrees (of any parent node) are perfect. This means all nodes in the tree have a balance factor that is 0, except maybe one or more nodes that are on the path from the root to the leftmost leaf: they may have a balance factor of 0 or −1 (When −1, this indicates their left subtree is one unit higher than their right subtree).

    2. The height of the tree is 𝐻𝑛 = ⌊log2𝑛⌋. By consequence, if 𝑛 is one less than a power of 2, the tree is a perfect tree and thus all balance factors are zero.

    3. The number of rotations is 𝑅𝑛 = 𝑛−1−𝐻𝑛

    Proof by induction

    Base case

    These invariants are true when 𝑛 is 1: that tree is perfect, 𝐻𝑛= 0, and the number of rotations is 𝑛−1−𝐻𝑛 = 0.

    Induction step

    We now assume a tree with 𝑛−1 nodes that obeys the invariants, and we then add the 𝑛th node (with smaller value) to that tree. We can distinguish between two cases:

    In conclusion: we have a proof by induction of the invariants. The third invariant is the one of interest:

          𝑅𝑛 = 𝑛−1−⌊log2𝑛⌋.