Question: Use the code provided to complete the problem in the picture using python with comments: class MinHeap: def _ _ init _ _ ( self
Use the code provided to complete the problem in the picture using python with comments:
class MinHeap:
def initself:
self.data # This list contains the heap elements
# The str method simply returns the elements of the heap, in list form
def strself:
return strselfdata
# Adds a new element to the heap
def addself newdata:
# First add the element to the end of the list maintains the complete
# tree property
self.data.appendnewdata
# Index of the last list element
index lenselfdata
# Do the "percolate up process swap the new node with its parent as
# many times as needed to maintain the minheap property
while index : # Loop exits once we reach the root index
# Compare this element vs its parent
parentindex index
# If the parent is larger than the child...
if self.dataparentindex self.dataindex:
# Swap the parent with the child
self.dataparentindex self.dataindex self.dataindex self.dataparentindex
# Update the current index
index parentindex
# If the parent is not larger than the child, the minheap
# property isn't violated and we can stop
else:
break
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
