Hello, I am wondering if these x's are in the right position for the min heap? Am I correct?
Asked
Active
Viewed 65 times
-3

Grant Winney
- 65,241
- 13
- 115
- 165

Tinler
- 165
- 6
-
I'm voting to close this question as off-topic because it is not a programming problem, it's a computer science problem. – gunr2171 Jul 05 '17 at 18:04
1 Answers
0
The top position is not a possibility because the 3 would be larger than its children (somewhere below would be a 1 or 2).
The second level is possible because 2 and 3 could be sibling children of 1.
To be on the third level, the 3 would need to have 2 for an immediate parent, and 1 for a grandparent with nothing else in between.
The fourth level is not possible because there you would need three ancestors of 3 that are smaller than three.
The list form is a direct conversion from the tree form. So, that is a match as well.
You might want to prove this yourself empirically by trying to insert every permutation of 9!
into minheap and observing where the 3 is found. Here is a Python script that does that:
from heapq import heapify
from itertools import permutations
has_three = [False] * 9
for t in permutations('123456789'):
s = list(t)
heapify(s)
i = s.index('3')
has_three[i] = True
print(has_three)
And the results are:
[False, True, True, True, True, True, True, False, False]

Raymond Hettinger
- 216,523
- 63
- 388
- 485