class Heaps:
def __init__(self):
self.data = []
def root_node(self):
return self.data[0]
def last_node(self):
return self.data[-1]
1. Array-Based Heap
2. Traversing an Array-Based Heap
2.1 Child of Any Node
To find the child of any node in an array-based heap, the following formula is always True
:
left_child:
(index*2)+1
right_child:
(index*2)+2
2.2 Child of Any Node: Code
def left_child_index(self, index):
return (index*2)+1
def right_child_index(self, index):
return (index*2)+2
2.3 Parent of Any Node
Any node’s parent:
(index-1)//2
(Note//
is floor division)
def parent_index(self, index):
return (index-1)//2
3. Insertion
def insert(self, value):
self.data.append(value)
= len(self.data)-1
new_node_index
while(new_node_index>0 and
self.data[new_node_index] > self.data[self.parent_index(new_node_index)])):
(= self.parent_index(new_node_index)
parent_index self.data[parent_index], self.data[new_node_index] = self.data[new_node_index], self.data[parent_index]
=parent_index new_node_index