My teacher asked this quesion in class, to find the minumum number of nodes in an AVL tree where the depth of the nearest leaf is K. But there is a catch, like we have to do it in O(1) time and not a recursive formulartion.
My approach is like this: For minimum number of nodes, the height of the tree also needs to be k(where k is the depth of the nearest leaf node). But after concluding this, the only approach that is coming to me is the recursive approach for minimum number of nodes in a AVL tree of height h,i.e., N(h) = N(h-1) + N(h-2) +1, with N(0)=0 and N(1) = 1. But my prof asked not to do it recursively and rather give a O(1) solution for this. Is it possible? If so can anyone please share some hints.
Yes, this is the correct approach.
By consequence, all root-to-leaf paths have length . If there would be a shorter path, then the nearest leaf node has a depth less than , and if there would be a longer path, the height of the tree would be more than .
In other words, all leaf nodes are at the bottom level of the tree. For instance, this is the case with a perfect binary tree.
We can however remove some leaves from a perfect binary tree without breaking the conditions, i.e. without reducing the height of the tree, and without creating new leaves (which would have less depth than ).
Example of a perfect tree (=3):
We can remove half of the leaves without creating new ones, nor breaking the AVL property, nor reducing the height:
We cannot remove more nodes without breaking one of the requirements.
The characteristic of this "minimal" tree is that it is a perfect tree of height −1 where each leaf gets a single child attached to it (it doesn't matter whether that is a left or right child).
How many nodes does such a tree have?
A perfect tree of height −1 has 2−1 nodes. It has 2−1 leaves. For each of those we have to count an extra node (to create the bottom level) so that in total we have 2−1 + 2−1 nodes, or otherwise put: 3∙2−1−1. For =0 (a single node), the answer is just 1.
As code: