AlgoFrames

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