max-heap
♦500
301
402
103
204
355
array form · child(i) = 2i+1, 2i+2
50
30
40
10
20
35
[0][1][2][3][4][5]
Concept
▸1// complete binary tree, stored as an array2parent(i) = ⌊(i−1)/2⌋3left(i) = 2i+1 right(i) = 2i+24peek(): return arr[0] // O(1)56push(x):7 append x; sift it UP8 while x > parent: swap up910pop():11 save arr[0]; move last leaf to root12 sift it DOWN13 while < larger child: swap down14 return saved
state
- typemax-heap
- root50