0

We learned in class that a binary heap has n/2 leaves, but does that have to assure us that the median of that heap is a leaf? Or can it also be a node who has a left/right child? Also, does this depend on n?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065

1 Answers1

0

Here's a counterexample using the numbers 1, 2, 3, 4, 5, 6, 7:

                  1
               4     2
              5 6   3 7

Here, the median is 4, and it's not in the bottom row.

Here's another example with 1, 2, 3, ..., 15: (median 8)

                         1
                8               2
            9      10        3     4
          11 12  13 14      5 6   7 15

If you have 2n - 1 total elements for n ≥ 3. You can then build a binary heap containing all those elements and with the median element (2n-1) in the second row as follows: put 1 at the top, put 2n-1 as its left child and 2 as its right child. Put the number 2n-1 + 1 through 2n - 2 as children of the median, and put the numbers 3 through 2n-1 - 1 and 2n - 1 as children of 2.

The only time this won't work is when you have 1 or 3 elements, since with one element the median is the only element and it's the root and with 3 elements the median can't be the root and therefore must be in the bottom row.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065