Parent and child indices
Warm-up · Fill in the code · about 5 min
A heap stores its tree in an array, root at index 0, level by level. Complete heapIndices(i) so it returns [parent, left, right] for the node at index i.
The root has no parent: return -1 for it.
Example 1
Input:
[4]
Output:
[1,9,10]
Index 4 sits under index 1 and has children 9 and 10.
Example 2
Input:
[0]
Output:
[-1,1,2]
The root has no parent.
Constraints
- 0 ≤ i ≤ 10,000
- The array is a complete tree, so every index up to the last one is filled
Learn the idea first: Binary heaps: array layout, sift up, sift down, a visual lesson.
More Binary heaps: array layout, sift up, sift down problems
- Which array is a min-heap? Warm-up
- Insert into a heap Warm-up
- Is this array a min-heap? Warm-up
- Extract the minimum Standard
- Implement push and pop Standard
- Spot the bug: sift down Standard
- Implement a max-heap with decrease-key Challenge