-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTree-Ex00.py
100 lines (92 loc) · 2.93 KB
/
BinaryTree-Ex00.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
class MaxHeap:
def __init__(self):
self.heap = []
def push(self,value):
self.heap.append(value)
self.float_up(len(self.heap)-1)
def float_up(self,index):
if index==0:
return
else:
if index%2==0:
parent_of_index = (index//2)-1
if self.heap[index]>self.heap[parent_of_index]:
temp = self.heap[parent_of_index]
self.heap[parent_of_index] = self.heap[index]
self.heap[index] = temp
else:
parent_of_index = index//2
if self.heap[index]> self.heap[parent_of_index]:
temp = self.heap[parent_of_index]
self.heap[parent_of_index] = self.heap[index]
self.heap[index] = temp
self.float_up(parent_of_index)
def peek(self):
print(self.heap[0])
def pop(self):
if len(self.heap)>=2:
temp = self.heap[0]
self.heap[0]=self.heap[len(self.heap)-1]
self.heap[len(self.heap)-1]
self.heap.pop()
self.down_adj()
elif len(self.heap)==1:
self.heap.pop()
else:
print("Nothing to pop")
def swap(self,index1,index2):
temp = self.heap[index1]
self.heap[index1] = self.heap[index2]
self.heap[index2] = temp
def down_adj(self):
index = 0
for i in range(len(self.heap)//2):
left_child = index*2+1
if left_child > len(self.heap)-1:
print(self.heap)
print("End Point")
print("Heap value after pop() = ",self.heap)
return
right_child = index*2+2
if right_child > len(self.heap)-1:
print("right child does not exist")
if self.heap[index]<self.heap[left_child]:
self.swap(index,left_child)
index = left_child
print("Heap value after pop() = ",self.heap)
return
if self.heap[index]<self.heap[left_child]:
if self.heap[left_child]<self.heap[right_child]:
self.swap(index,right_child)
index = right_child
else:
self.swap(index,left_child)
index = left_child
elif self.heap[index] < self.heap[right_child]:
self.swap(index,right_child)
index = right_child
else:
print("No change required")
print("heap value after pop() = ",self.heap)
H = MaxHeap()
print("******pushing values*****")
H.push(165)
print(H.heap)
H.push(60)
print(H.heap)
H.push(179)
print(H.heap)
H.push(400)
print(H.heap)
H.push(6)
print(H.heap)
H.push(275)
print(H.heap)
print("*******poping values*****")
H.pop()
H.pop()
H.pop()
H.pop()
H.pop()
H.pop()
H.pop()