0

I am currently doing a max-heap. When I use remove() method, I understand that I would swap with the larger children. What if both of the children have the same priority? for instance

Case 1:

heap = [5,7,7,16,15]

if I remove 5 and replace it with 15, I would trickle down to the right (which is wrong), so I would trickle down to the left side.

but using the same logic, if i have

heap = [5,7,7,16,15,18]

and I trickle down left, it will no longer be a valid heap.

What can I do to ensure I have a valid heap?

Sugihara
  • 1,091
  • 2
  • 20
  • 35

1 Answers1

0

It does not matter.

Trickling down to the right in the first case is fine:

[15, 7, 7, 16] -> [7, 7, 15, 16]

Trickling down to the left in the first case is fine:

[15, 7, 7, 16] -> [7, 15, 7, 16]

Trickling down to the right in the second case is fine:

[18, 7, 7, 16, 15] -> [7, 7, 18, 16, 15]

Trickling down to the left in the second case is fine:

[18, 7, 7, 16, 15] -> [7, 18, 7, 16, 15] -> [7, 15, 7, 16, 18]

Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51