Consider a binary min-heap containing distinct elements. Let be the index (in the underlying array) of the maximum element stored in the heap. The number of possible values of is
View worked solution
Answer: A
In a binary min-heap, the value of any node is smaller than or equal to the values of its children. Consequently, the maximum element in a min-heap cannot have any children (if it did, those children would have to be larger than the maximum element, which is a contradiction).
Therefore, the maximum element must reside at one of the leaf nodes of the heap.
For a complete binary tree represented as an array of size (using 1-based indexing):
- The parent of the last element (at index ) is at index .
- Thus, all nodes from index to are internal nodes (they have at least one child).
- The leaf nodes are located at indices from to .
Given :
So, the leaf nodes are located at indices from to .
The number of leaf nodes (and thus the number of possible positions for the maximum element) is:
Hence, there are possible values for the index .
Free practice · Your answers on this page are not saved.
