1
$\begingroup$

According to Wikipedia's entry on binary heaps:

The Build-Max-Heap function that follows, converts an array A which stores a complete binary tree with n nodes to a max-heap by repeatedly using Max-Heapify (down-heapify for a max-heap) in a bottom-up manner. The array elements indexed by floor(n/2) + 1, floor(n/2) + 2, ..., n are all leaves for the tree (assuming that indices start at 1)—thus each is a one-element heap, and does not need to be down-heapified. Build-Max-Heap runs Max-Heapify on each of the remaining tree nodes.

Build-Max-Heap (A): >> for each index i from floor(length(A)/2) down to 1 do: Max-Heapify(A, i)

I also know that to represent a binary tree as an array, you place the root at index 0. Then, left child at indexOfParent*2 + 1 and right child at indexOfParent*2 + 2 is performed for all subsequent nodes

Now, supposing I have a very unbalanced binary tree represented as follows:

 3
 1 8
 45 7
 6
 52
 94

Representing this binary tree as an array with elements (x,n), x is value of a node, n being index of that value within the array, I get arr = [(3,0),(1,1), (8,2), (45,3) (7,6), (6,14),(52,30),(94,62)]

Because of how unbalanced this tree, there are so many chunks in the array with no values. Regardless, we know this array has a length of 62. Back to the formula , n//2 implies 62//2 = 31. Therefore, according to the equation, all values in the array with index < 31 are non-leaf

Yet value 45 at index 3 is very clearly a leaf node. Back to the Wikipedia definition, The array elements indexed by floor(n/2) + 1, floor(n/2) + 2, ..., n are all leaves for the tree

Does this not contradict the value 45 being at index 3 then? I might then try to remove all the 'gaps' in the array but that would represent a completely different binary tree (a balanced one)

So how does the equation for calculating non-leaf nodes work on such unbalanced binary trees?

asked yesterday
$\endgroup$
1
  • $\begingroup$ Your tree is not a binary heap, so why would you expect that it has that property? Also, the length of the array is 63. $\endgroup$ Commented yesterday

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.