Question: Describe how you would use a binary heap to
manage the posts and ensure that they are displayed in the
order of their popularity. How would you handle the
addition of new posts and the removal of unpopular posts?
Answer:
A= Atif (7.3M)
B= Sheraz (1.7M)
C= Shahbaz (2.1M)
D= Shahzad (3M)
E= Sara (7.1M)
F= Abbas (1M)
G= Halima (33.2K)
H= Aryan (1.1M)
I= Ahad (4.4M)
J= Shanzay (545K)
First we can make the binary tree into max heap:
B
C
D E F G
H I J
1)
A
B<E So, we can
B
swap E with B C
for max heap
D E F G
H I J
2)
A
D<I So, we can
swap I with D
for max heap
E
C
D B F G
H I J
3) This binary tree is now in max heap
E
C
I B F G
H D J
Delete the max element from this binary
tree:
A is the largest
element in this
A
binary tree so
we can delete A
E
C
I B F G
H D J
Max-Element
A is deleted
E
C
I B F G
H D J
Condition to delete max heap from binary tree:
The standard deletion operation on Heap is to delete the element
present at the root node of the heap. That is if it’s is a Max
Heap, the standard deletion operation will delete the max
element and if it’s is a Min Heap, it will delete the min element.
Insert R in binary tree:
R is the insert in
this binary tree
R
where we can
delete the A
element.
E
C
I B F G
H D J
Condition to insert element in binary tree:
Given a binary heap and a new element to be added to this heap.
The task is to insert the new element to the heap maintaining the
properties of heap.
Now again delete the max element:
R
E is the largest
element in this
binary tree so E
C
we can delete E
I B F G
H D J
Max-Element
E is deleted C
I B F G
H D J
Insert S in binary tree:
S is the insert in
this binary tree
S
where we can C
delete the E
element.
I B F G
H D J