Reputation: 519
Question: Where in a max-heap might the smallest element reside, assuming that all elements are distinct?
I understand that in a max-heap, the largest node is the root and the smallest is one of the leaves. I found answer which says that it's in any of the any of the leaves, that is, elements with index ⌊n/2⌋+k
, where k>=1
, that is, in the second half of the heap array.
Problem: can you please explain why the answer I found do not just say it's one of the leaves? Can you please explain why answer brough ⌊n/2⌋+k
? Second, why in the second half, when it's in the last level of the tree given that all parents are greater than their children, so a child at height 1 is smaller than parent but larger than its child and so on.
Edited: Can you please explain why the indices of the leaves are ⌊n/2⌋+1, ⌊n/2⌋+2, ..., ⌊n/2⌋+n
? Or why the index of the last non-leaf node is at ⌊n/2⌋
of array-based heap please? We know that total vertices of heap is given by Ceil(n/2^(h+1))
. The leaves number is Ceil(n/2)
, so hope the extra details would help solving the question.
Upvotes: 0
Views: 1058
Reputation: 350300
In a zero-based indexed array, the root is at index 0. The children of the root are at index 1 and 2. In general the children of index 𝑖 are at indices 2𝑖+1 and 2𝑖+2.
So for a node to have children, we must have that 2𝑖+1 (i.e. the left child) is still within the range of the array, i.e. 2𝑖+1 < 𝑛, where 𝑛 is the size of the array (i.e. the last index is at 𝑛-1).
Which is the index of the first leaf? That would be the least value of 𝑖 for which 2𝑖+1 < 𝑛 is not true, i.e. when 2𝑖+1 ≥ 𝑛. From that we can derive that:
All indices that represent leaves are grouped together. They are all at the 𝑖, for which 2𝑖+1 ≥ 𝑛
The least index of a leaf is at index 𝑖 = ⌊𝑛/2⌋.
If you are working with a one-based indexed array (as is common in pseudo code), then you can adapt the above reasoning to derive that the first leaf is at index 𝑖 = ⌊𝑛/2⌋+1.
So the answer you quote is assuming a 1-based indexed array, and then it is correct to say that the first leaf is positioned at ⌊𝑛/2⌋+1, and any leaf is at a position ⌊𝑛/2⌋+𝑘, where 𝑘≥1.
Upvotes: 3