algorithm - Does the median value in a heap have to be in the bottom row? -
we learned in class binary heap has n/2 leaves, have assure median of heap leaf? or can node has left/right child? also, depend on n?
here's counterexample using numbers 1, 2, 3, 4, 5, 6, 7:
1 4 2 5 6 3 7
here, median 4, , it's not in bottom row.
here's example 1, 2, 3, ..., 15: (median 8)
1 8 2 9 10 3 4 11 12 13 14 5 6 7 15
if have 2n - 1 total elements n ≥ 3. can build binary heap containing elements , median element (2n-1) in second row follows: put 1 @ top, put 2n-1 left child , 2 right child. put number 2n-1 + 1 through 2n - 2 children of median, , put numbers 3 through 2n-1 - 1 , 2n - 1 children of 2.
the time won't work when have 1 or 3 elements, since 1 element median element , it's root , 3 elements median can't root , therefore must in bottom row.
hope helps!
Comments
Post a Comment