Binary Heaps Flashcards
1
Q
how to construct an array backed min heap, without using buildHeap()
A
for every item in the array call add() method, which results in O(nlogn) method, becasue each add costs O(logn)
2
Q
given data at index n for a binary heap,
- what’s its left child’s index
- what’s its right child’s index
- what’s its parent’s index
A
- what’s its left child’s index: 2n
- what’s its right child’s index: 2n + 1
- what’s its parent’s index: n/2
3
Q
how does buildHeap( ) work and what’s its time complexity
A
use recursion to build valid subheaps incrementally that eventually assemble into the complete heap
1. loop from size/2 to 1
2. call the method itself to determine if a swap between the parent and any of its children is needed
time compelxity is O(n)
4
Q
how does add work in a heap
A
- add to the back of the array
- perform up-heap
5
Q
how does remove work in a heap
A
- move the last element to replace the root
- perform down-heap