Hands-On Data Structures and Algorithms with Python, Third Edition by Dr. Basant Agarwal

Hands-On Data Structures and Algorithms with Python, Third Edition by Dr. Basant Agarwal

Author:Dr. Basant Agarwal
Language: eng
Format: epub
Tags: COM051360 - COMPUTERS / Programming Languages / Python, COM051300 - COMPUTERS / Programming / Algorithms, COM051000 - COMPUTERS / Programming / General
Publisher: Packt
Published: 2022-07-18T12:32:26+00:00


The output of the above code is as follows:

[0, 2, 3, 5, 7, 9, 10, 6] 2 [0, 3, 6, 5, 7, 9, 10]

We can see in the output that the root element 2 is returned in the new heap, and that the data elements are rearranged so that all the nodes of the heap are following the heap property (indexes of the nodes can checked as shown in Figure 7.16). Next, we will discuss if we want to delete any node with the given index position.

Deleting an element at a specific location from a heap

Generally, we delete an element at the root, however, an element can be deleted at a specific location from the heap. Let us understand it with an example. Given the following heap, let’s assume that we want to delete a node with value 3 at index 2. After deleting the node with value 3, we move the last node to the deleted node, in other words, the node with value 15, as shown in Figure 7.16:

Figure 7.16: The deletion of node 3 from the heap

After shifting the last element to the deleted node, we compare this with its root element since it is already greater than the root element, so we do not swap. Next, we compare this element with all of its children, and since the left child is smaller, it is swapped with the left child, as shown in Figure 7.17:

Figure 7.17: A comparison of node 15 with 5 and 11, and swapping node 15 and node 5

After swapping node 15 with node 5, we move down in the heap. Next, we compare node 15 with its child, node 8. Finally, node 8 and node 15 are swapped. Now, the final tree follows the heap property, as shown in Figure 7.18:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.