69.4k views
3 votes
Basic Binary Heap Operation (a) Starting from an empty binary heap, what is the resulting heap after successively inserting 1, 2, 9, 7, 5, 8, 3, 4, and 6? Please show your steps. (b) Remove the minimum element of the previous resulting heap. Please show your steps.

User Tomekwi
by
8.5k points

1 Answer

3 votes

The resulting binary heap after successively inserting 1, 2, 9, 7, 5, 8, 3, 4, and 6 is:

9

7 8

5 6 3 4

1 2

To build the binary heap, we start with an empty heap and insert the elements one by one, following the heap property. In a binary heap, each parent node is greater than or equal to its children (for a max heap).

1. Inserting 1: We insert 1 as the root node.

1

2. Inserting 2: Since 2 is greater than 1, it becomes the left child of 1.

2

/

1

3. Inserting 9: 9 is greater than both 1 and 2, so it becomes the new root.

9

/

2

/

1

4. Inserting 7: 7 is less than 9 but greater than 2 and 1. It becomes the right child of 9.

9

/ \

2 7

/

1

5. Inserting 5: 5 is less than 9 but greater than 2, 7, and 1. It becomes the left child of 2.

9

/ \

2 7

/ \

1 5

6. Inserting 8: 8 is less than 9 but greater than 2, 7, and 1. It becomes the right child of 2.

9

/ \

2 7

/ \

1 5

/

8

7. Inserting 3: 3 is less than 9 but greater than 2, 7, and 1. It becomes the left child of 7.

9

/ \

2 7

/ \

1 5

/ \

8 3

8. Inserting 4: 4 is less than 9 but greater than 2, 7, and 1. It becomes the right child of 7.

9

/ \

2 7

/ \

1 5

/ \

8 3

\

4

9. Inserting 6: 6 is less than 9 but greater than 2, 7, and 1. It becomes the left child of 5.

9

/ \

2 7

/ \

1 5

/ \

8 3

/ \

6 4

(b) After removing the minimum element (1) from the previous heap:

The resulting binary heap is:

9

7 8

5 6 3 4

2

To remove the minimum element from a binary heap, we replace it with the last element in the heap and then apply heapify to restore the heap property. In this case, the minimum element is 1, which is replaced with the last element, 6.

1. Replace 1 with 6:

9

/ \

2 7

/ \

6 5

/ \

8 3

/

4

2. Apply heapify to restore the heap property:

9

/ \

2 7

/ \

4 5

/ \

8

User Casie
by
7.6k points