2

I have a question: given that an AVL tree holds numbers 1, 2, 3, ..., 1000, what are the smallest and largest possible values of the root?

I have a feeling it is 500 and 501, but I don't know how to prove this.

To start with, I created a formula using a recurrence $N(h)=N(h-1)+N(h-2)+1$ for the minimum number of nodes given an AVL tree of height $h$, $N(h)$. This comes out as $$N(h)=\frac{5+10\sqrt{5}}{5}\left(\frac{1+\sqrt{5}}{2}\right)^h+\frac{5-10\sqrt{5}}{5}\left(\frac{1-\sqrt{5}}{2}\right)^h$$and the maximum value for an AVL tree of height $h$ is clearly $M(h)=2^{h+1}-1$.

Since we're working with an AVL tree the left and right subtrees of the root must have heights differing by at most 1.

To find the smallest root value, we need as few numbers in the left subtree as possible. This means we also want to minimise the height, but we also require that the height $h_L$ is no smaller than $h_R-1$. Setting $h_R=h_L+1$ I tried using $N(h_L)+M(h_L+1)=1000$, but I'm really not sure how this would help.

I would ideally prefer to find a much less maths-based solution for this problem. Could anyone help?

HBH
  • 21
  • 1

1 Answers1

1

The objective is to find the minimum and maximum possible values of the root of an AVL tree that contains keys $1,2,\ldots,1000$. Let $N(h)$ denote the minimum number of nodes in an AVL tree that contains $h$ levels (including the root). Thus, $N(1)=1, N(2)=2$, and $N(h) = N(h-1)+N(h-2)+1, \forall h \ge 3$. Let $M(h)$ denote the maximum number of nodes in an AVL tree that contains $h$ levels (including the root). Thus, $M(h) = 2^h - 1$. Using these recurrences, one obtains the following table of values:

$$\begin{array}{c|cc} h&1&2&3&4&5&6&7&8&9&10&\\ \hline N(h)&1&2&4&7&12&20&33&54&88&143\\ M(h)&1&3&7&15&31&63&127&255&511&1023 \end{array}$$

If the AVL tree has 10 levels, say the left subtree of root has 8 levels and the right subtree has 9 levels, then the tree contains at most $M(8)+M(9) + 1 < 1000$ nodes. The smallest number of levels $h$ such that $N(h-2)+M(h-1)+1$ is at least $1000$ is $11$ levels.

So suppose the AVL tree has 11 levels. In order to find the minimum possible value of the root, create an extreme imbalance by choosing the left subtree to contain $9$ levels and the right subtree to contain $10$ levels, such that the left subtree contains the smallest possible number of nodes, namely $N(9)=88$ nodes. So, the smallest possible value of the root is $N(9)+1 = 89$, with keys $90,\ldots,1000$ in the right subtree of the root. A similar argument that swaps the left and right subtrees puts $88$ nodes in the right subtree and gives the root a value of $1000-N(9)=912$. The possible values of the root are $89,90, \ldots, 912$.

Ashwin Ganesan
  • 1,388
  • 7
  • 10