forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathavl_tree.py
349 lines (296 loc) · 9.47 KB
/
avl_tree.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
"""
Implementation of an auto-balanced binary tree!
For doctests run following command:
python3 -m doctest -v avl_tree.py
For testing run:
python avl_tree.py
"""
from __future__ importannotations
importmath
importrandom
fromtypingimportAny
classMyQueue:
def__init__(self) ->None:
self.data: list[Any] = []
self.head: int=0
self.tail: int=0
defis_empty(self) ->bool:
returnself.head==self.tail
defpush(self, data: Any) ->None:
self.data.append(data)
self.tail=self.tail+1
defpop(self) ->Any:
ret=self.data[self.head]
self.head=self.head+1
returnret
defcount(self) ->int:
returnself.tail-self.head
defprint_queue(self) ->None:
print(self.data)
print("**************")
print(self.data[self.head : self.tail])
classMyNode:
def__init__(self, data: Any) ->None:
self.data=data
self.left: MyNode|None=None
self.right: MyNode|None=None
self.height: int=1
defget_data(self) ->Any:
returnself.data
defget_left(self) ->MyNode|None:
returnself.left
defget_right(self) ->MyNode|None:
returnself.right
defget_height(self) ->int:
returnself.height
defset_data(self, data: Any) ->None:
self.data=data
defset_left(self, node: MyNode|None) ->None:
self.left=node
defset_right(self, node: MyNode|None) ->None:
self.right=node
defset_height(self, height: int) ->None:
self.height=height
defget_height(node: MyNode|None) ->int:
ifnodeisNone:
return0
returnnode.get_height()
defmy_max(a: int, b: int) ->int:
ifa>b:
returna
returnb
defright_rotation(node: MyNode) ->MyNode:
r"""
A B
/ \ / \
B C Bl A
/ \ --> / / \
Bl Br UB Br C
/
UB
UB = unbalanced node
"""
print("left rotation node:", node.get_data())
ret=node.get_left()
assertretisnotNone
node.set_left(ret.get_right())
ret.set_right(node)
h1=my_max(get_height(node.get_right()), get_height(node.get_left())) +1
node.set_height(h1)
h2=my_max(get_height(ret.get_right()), get_height(ret.get_left())) +1
ret.set_height(h2)
returnret
defleft_rotation(node: MyNode) ->MyNode:
"""
a mirror symmetry rotation of the left_rotation
"""
print("right rotation node:", node.get_data())
ret=node.get_right()
assertretisnotNone
node.set_right(ret.get_left())
ret.set_left(node)
h1=my_max(get_height(node.get_right()), get_height(node.get_left())) +1
node.set_height(h1)
h2=my_max(get_height(ret.get_right()), get_height(ret.get_left())) +1
ret.set_height(h2)
returnret
deflr_rotation(node: MyNode) ->MyNode:
r"""
A A Br
/ \ / \ / \
B C LR Br C RR B A
/ \ --> / \ --> / / \
Bl Br B UB Bl UB C
\ /
UB Bl
RR = right_rotation LR = left_rotation
"""
left_child=node.get_left()
assertleft_childisnotNone
node.set_left(left_rotation(left_child))
returnright_rotation(node)
defrl_rotation(node: MyNode) ->MyNode:
right_child=node.get_right()
assertright_childisnotNone
node.set_right(right_rotation(right_child))
returnleft_rotation(node)
definsert_node(node: MyNode|None, data: Any) ->MyNode|None:
ifnodeisNone:
returnMyNode(data)
ifdata<node.get_data():
node.set_left(insert_node(node.get_left(), data))
if (
get_height(node.get_left()) -get_height(node.get_right()) ==2
): # an unbalance detected
left_child=node.get_left()
assertleft_childisnotNone
if (
data<left_child.get_data()
): # new node is the left child of the left child
node=right_rotation(node)
else:
node=lr_rotation(node)
else:
node.set_right(insert_node(node.get_right(), data))
ifget_height(node.get_right()) -get_height(node.get_left()) ==2:
right_child=node.get_right()
assertright_childisnotNone
ifdata<right_child.get_data():
node=rl_rotation(node)
else:
node=left_rotation(node)
h1=my_max(get_height(node.get_right()), get_height(node.get_left())) +1
node.set_height(h1)
returnnode
defget_right_most(root: MyNode) ->Any:
whileTrue:
right_child=root.get_right()
ifright_childisNone:
break
root=right_child
returnroot.get_data()
defget_left_most(root: MyNode) ->Any:
whileTrue:
left_child=root.get_left()
ifleft_childisNone:
break
root=left_child
returnroot.get_data()
defdel_node(root: MyNode, data: Any) ->MyNode|None:
left_child=root.get_left()
right_child=root.get_right()
ifroot.get_data() ==data:
ifleft_childisnotNoneandright_childisnotNone:
temp_data=get_left_most(right_child)
root.set_data(temp_data)
root.set_right(del_node(right_child, temp_data))
elifleft_childisnotNone:
root=left_child
elifright_childisnotNone:
root=right_child
else:
returnNone
elifroot.get_data() >data:
ifleft_childisNone:
print("No such data")
returnroot
else:
root.set_left(del_node(left_child, data))
# root.get_data() < data
elifright_childisNone:
returnroot
else:
root.set_right(del_node(right_child, data))
# Re-fetch left_child and right_child references
left_child=root.get_left()
right_child=root.get_right()
ifget_height(right_child) -get_height(left_child) ==2:
assertright_childisnotNone
ifget_height(right_child.get_right()) >get_height(right_child.get_left()):
root=left_rotation(root)
else:
root=rl_rotation(root)
elifget_height(right_child) -get_height(left_child) ==-2:
assertleft_childisnotNone
ifget_height(left_child.get_left()) >get_height(left_child.get_right()):
root=right_rotation(root)
else:
root=lr_rotation(root)
height=my_max(get_height(root.get_right()), get_height(root.get_left())) +1
root.set_height(height)
returnroot
classAVLtree:
"""
An AVL tree doctest
Examples:
>>> t = AVLtree()
>>> t.insert(4)
insert:4
>>> print(str(t).replace(" \\n","\\n"))
4
*************************************
>>> t.insert(2)
insert:2
>>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n"))
4
2 *
*************************************
>>> t.insert(3)
insert:3
right rotation node: 2
left rotation node: 4
>>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n"))
3
2 4
*************************************
>>> t.get_height()
2
>>> t.del_node(3)
delete:3
>>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n"))
4
2 *
*************************************
"""
def__init__(self) ->None:
self.root: MyNode|None=None
defget_height(self) ->int:
returnget_height(self.root)
definsert(self, data: Any) ->None:
print("insert:"+str(data))
self.root=insert_node(self.root, data)
defdel_node(self, data: Any) ->None:
print("delete:"+str(data))
ifself.rootisNone:
print("Tree is empty!")
return
self.root=del_node(self.root, data)
def__str__(
self,
) ->str: # a level traversale, gives a more intuitive look on the tree
output=""
q=MyQueue()
q.push(self.root)
layer=self.get_height()
iflayer==0:
returnoutput
cnt=0
whilenotq.is_empty():
node=q.pop()
space=" "*int(math.pow(2, layer-1))
output+=space
ifnodeisNone:
output+="*"
q.push(None)
q.push(None)
else:
output+=str(node.get_data())
q.push(node.get_left())
q.push(node.get_right())
output+=space
cnt=cnt+1
foriinrange(100):
ifcnt==math.pow(2, i) -1:
layer=layer-1
iflayer==0:
output+="\n*************************************"
returnoutput
output+="\n"
break
output+="\n*************************************"
returnoutput
def_test() ->None:
importdoctest
doctest.testmod()
if__name__=="__main__":
_test()
t=AVLtree()
lst=list(range(10))
random.shuffle(lst)
foriinlst:
t.insert(i)
print(str(t))
random.shuffle(lst)
foriinlst:
t.del_node(i)
print(str(t))