Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 51k
Expand file tree
/
Copy pathbinary_search_tree_recursive.py
More file actions
Latest commit
641 lines (536 loc) · 16.1 KB
/
Copy pathbinary_search_tree_recursive.py
File metadata and controls
641 lines (536 loc) · 16.1 KB
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
"""
This is a python3 implementation of binary search tree using recursion
To run tests:
python -m unittest binary_search_tree_recursive.py
To run an example:
python binary_search_tree_recursive.py
"""
from __future__ importannotations
importunittest
fromcollections.abcimportIterator
importpytest
classNode:
def__init__(self, label: int, parent: Node|None) ->None:
self.label=label
self.parent=parent
self.left: Node|None=None
self.right: Node|None=None
classBinarySearchTree:
def__init__(self) ->None:
self.root: Node|None=None
defempty(self) ->None:
"""
Empties the tree
>>> t = BinarySearchTree()
>>> assert t.root is None
>>> t.put(8)
>>> assert t.root is not None
"""
self.root=None
defis_empty(self) ->bool:
"""
Checks if the tree is empty
>>> t = BinarySearchTree()
>>> t.is_empty()
True
>>> t.put(8)
>>> t.is_empty()
False
"""
returnself.rootisNone
defput(self, label: int) ->None:
"""
Put a new node in the tree
>>> t = BinarySearchTree()
>>> t.put(8)
>>> assert t.root.parent is None
>>> assert t.root.label == 8
>>> t.put(10)
>>> assert t.root.right.parent == t.root
>>> assert t.root.right.label == 10
>>> t.put(3)
>>> assert t.root.left.parent == t.root
>>> assert t.root.left.label == 3
"""
self.root=self._put(self.root, label)
def_put(self, node: Node|None, label: int, parent: Node|None=None) ->Node:
ifnodeisNone:
node=Node(label, parent)
eliflabel<node.label:
node.left=self._put(node.left, label, node)
eliflabel>node.label:
node.right=self._put(node.right, label, node)
else:
msg=f"Node with label {label} already exists"
raiseValueError(msg)
returnnode
defsearch(self, label: int) ->Node:
"""
Searches a node in the tree
>>> t = BinarySearchTree()
>>> t.put(8)
>>> t.put(10)
>>> node = t.search(8)
>>> assert node.label == 8
>>> node = t.search(3)
Traceback (most recent call last):
...
ValueError: Node with label 3 does not exist
"""
returnself._search(self.root, label)
def_search(self, node: Node|None, label: int) ->Node:
ifnodeisNone:
msg=f"Node with label {label} does not exist"
raiseValueError(msg)
eliflabel<node.label:
node=self._search(node.left, label)
eliflabel>node.label:
node=self._search(node.right, label)
returnnode
defremove(self, label: int) ->None:
"""
Removes a node in the tree
>>> t = BinarySearchTree()
>>> t.put(8)
>>> t.put(10)
>>> t.remove(8)
>>> assert t.root.label == 10
>>> t.remove(3)
Traceback (most recent call last):
...
ValueError: Node with label 3 does not exist
"""
node=self.search(label)
ifnode.rightandnode.left:
lowest_node=self._get_lowest_node(node.right)
lowest_node.left=node.left
lowest_node.right=node.right
node.left.parent=lowest_node
ifnode.right:
node.right.parent=lowest_node
self._reassign_nodes(node, lowest_node)
elifnotnode.rightandnode.left:
self._reassign_nodes(node, node.left)
elifnode.rightandnotnode.left:
self._reassign_nodes(node, node.right)
else:
self._reassign_nodes(node, None)
def_reassign_nodes(self, node: Node, new_children: Node|None) ->None:
ifnew_children:
new_children.parent=node.parent
ifnode.parent:
ifnode.parent.right==node:
node.parent.right=new_children
else:
node.parent.left=new_children
else:
self.root=new_children
def_get_lowest_node(self, node: Node) ->Node:
ifnode.left:
lowest_node=self._get_lowest_node(node.left)
else:
lowest_node=node
self._reassign_nodes(node, node.right)
returnlowest_node
defexists(self, label: int) ->bool:
"""
Checks if a node exists in the tree
>>> t = BinarySearchTree()
>>> t.put(8)
>>> t.put(10)
>>> t.exists(8)
True
>>> t.exists(3)
False
"""
try:
self.search(label)
returnTrue
exceptValueError:
returnFalse
defget_max_label(self) ->int:
"""
Gets the max label inserted in the tree
>>> t = BinarySearchTree()
>>> t.get_max_label()
Traceback (most recent call last):
...
ValueError: Binary search tree is empty
>>> t.put(8)
>>> t.put(10)
>>> t.get_max_label()
10
"""
ifself.rootisNone:
raiseValueError("Binary search tree is empty")
node=self.root
whilenode.rightisnotNone:
node=node.right
returnnode.label
defget_min_label(self) ->int:
"""
Gets the min label inserted in the tree
>>> t = BinarySearchTree()
>>> t.get_min_label()
Traceback (most recent call last):
...
ValueError: Binary search tree is empty
>>> t.put(8)
>>> t.put(10)
>>> t.get_min_label()
8
"""
ifself.rootisNone:
raiseValueError("Binary search tree is empty")
node=self.root
whilenode.leftisnotNone:
node=node.left
returnnode.label
definorder_traversal(self) ->Iterator[Node]:
"""
Return the inorder traversal of the tree
>>> t = BinarySearchTree()
>>> [i.label for i in t.inorder_traversal()]
[]
>>> t.put(8)
>>> t.put(10)
>>> t.put(9)
>>> [i.label for i in t.inorder_traversal()]
[8, 9, 10]
"""
returnself._inorder_traversal(self.root)
def_inorder_traversal(self, node: Node|None) ->Iterator[Node]:
ifnodeisnotNone:
yieldfromself._inorder_traversal(node.left)
yieldnode
yieldfromself._inorder_traversal(node.right)
defpreorder_traversal(self) ->Iterator[Node]:
"""
Return the preorder traversal of the tree
>>> t = BinarySearchTree()
>>> [i.label for i in t.preorder_traversal()]
[]
>>> t.put(8)
>>> t.put(10)
>>> t.put(9)
>>> [i.label for i in t.preorder_traversal()]
[8, 10, 9]
"""
returnself._preorder_traversal(self.root)
def_preorder_traversal(self, node: Node|None) ->Iterator[Node]:
ifnodeisnotNone:
yieldnode
yieldfromself._preorder_traversal(node.left)
yieldfromself._preorder_traversal(node.right)
classBinarySearchTreeTest(unittest.TestCase):
@staticmethod
def_get_binary_search_tree() ->BinarySearchTree:
r"""
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
\
5
"""
t=BinarySearchTree()
t.put(8)
t.put(3)
t.put(6)
t.put(1)
t.put(10)
t.put(14)
t.put(13)
t.put(4)
t.put(7)
t.put(5)
returnt
deftest_put(self) ->None:
t=BinarySearchTree()
assertt.is_empty()
t.put(8)
r"""
8
"""
assertt.rootisnotNone
assertt.root.parentisNone
assertt.root.label==8
t.put(10)
r"""
8
\
10
"""
assertt.root.rightisnotNone
assertt.root.right.parent==t.root
assertt.root.right.label==10
t.put(3)
r"""
8
/ \
3 10
"""
assertt.root.leftisnotNone
assertt.root.left.parent==t.root
assertt.root.left.label==3
t.put(6)
r"""
8
/ \
3 10
\
6
"""
assertt.root.left.rightisnotNone
assertt.root.left.right.parent==t.root.left
assertt.root.left.right.label==6
t.put(1)
r"""
8
/ \
3 10
/ \
1 6
"""
assertt.root.left.leftisnotNone
assertt.root.left.left.parent==t.root.left
assertt.root.left.left.label==1
withpytest.raises(ValueError):
t.put(1)
deftest_search(self) ->None:
t=self._get_binary_search_tree()
node=t.search(6)
assertnode.label==6
node=t.search(13)
assertnode.label==13
withpytest.raises(ValueError):
t.search(2)
deftest_remove(self) ->None:
t=self._get_binary_search_tree()
t.remove(13)
r"""
8
/ \
3 10
/ \ \
1 6 14
/ \
4 7
\
5
"""
assertt.rootisnotNone
assertt.root.rightisnotNone
assertt.root.right.rightisnotNone
assertt.root.right.right.rightisNone
assertt.root.right.right.leftisNone
t.remove(7)
r"""
8
/ \
3 10
/ \ \
1 6 14
/
4
\
5
"""
assertt.root.leftisnotNone
assertt.root.left.rightisnotNone
assertt.root.left.right.leftisnotNone
assertt.root.left.right.rightisNone
assertt.root.left.right.left.label==4
t.remove(6)
r"""
8
/ \
3 10
/ \ \
1 4 14
\
5
"""
assertt.root.left.leftisnotNone
assertt.root.left.right.rightisnotNone
assertt.root.left.left.label==1
assertt.root.left.right.label==4
assertt.root.left.right.right.label==5
assertt.root.left.right.leftisNone
assertt.root.left.left.parent==t.root.left
assertt.root.left.right.parent==t.root.left
t.remove(3)
r"""
8
/ \
4 10
/ \ \
1 5 14
"""
assertt.rootisnotNone
assertt.root.left.label==4
assertt.root.left.right.label==5
assertt.root.left.left.label==1
assertt.root.left.parent==t.root
assertt.root.left.left.parent==t.root.left
assertt.root.left.right.parent==t.root.left
t.remove(4)
r"""
8
/ \
5 10
/ \
1 14
"""
assertt.root.leftisnotNone
assertt.root.left.leftisnotNone
assertt.root.left.label==5
assertt.root.left.rightisNone
assertt.root.left.left.label==1
assertt.root.left.parent==t.root
assertt.root.left.left.parent==t.root.left
deftest_remove_2(self) ->None:
t=self._get_binary_search_tree()
t.remove(3)
r"""
8
/ \
4 10
/ \ \
1 6 14
/ \ /
5 7 13
"""
assertt.rootisnotNone
assertt.root.leftisnotNone
assertt.root.left.leftisnotNone
assertt.root.left.rightisnotNone
assertt.root.left.right.leftisnotNone
assertt.root.left.right.rightisnotNone
assertt.root.left.label==4
assertt.root.left.right.label==6
assertt.root.left.left.label==1
assertt.root.left.right.right.label==7
assertt.root.left.right.left.label==5
assertt.root.left.parent==t.root
assertt.root.left.right.parent==t.root.left
assertt.root.left.left.parent==t.root.left
assertt.root.left.right.left.parent==t.root.left.right
deftest_empty(self) ->None:
t=self._get_binary_search_tree()
t.empty()
assertt.rootisNone
deftest_is_empty(self) ->None:
t=self._get_binary_search_tree()
assertnott.is_empty()
t.empty()
assertt.is_empty()
deftest_exists(self) ->None:
t=self._get_binary_search_tree()
assertt.exists(6)
assertnott.exists(-1)
deftest_get_max_label(self) ->None:
t=self._get_binary_search_tree()
assertt.get_max_label() ==14
t.empty()
withpytest.raises(ValueError):
t.get_max_label()
deftest_get_min_label(self) ->None:
t=self._get_binary_search_tree()
assertt.get_min_label() ==1
t.empty()
withpytest.raises(ValueError):
t.get_min_label()
deftest_inorder_traversal(self) ->None:
t=self._get_binary_search_tree()
inorder_traversal_nodes= [i.labelforiint.inorder_traversal()]
assertinorder_traversal_nodes== [1, 3, 4, 5, 6, 7, 8, 10, 13, 14]
deftest_preorder_traversal(self) ->None:
t=self._get_binary_search_tree()
preorder_traversal_nodes= [i.labelforiint.preorder_traversal()]
assertpreorder_traversal_nodes== [8, 3, 1, 6, 4, 5, 7, 10, 14, 13]
defbinary_search_tree_example() ->None:
r"""
Example
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
\
5
Example After Deletion
4
/ \
1 7
\
5
"""
t=BinarySearchTree()
t.put(8)
t.put(3)
t.put(6)
t.put(1)
t.put(10)
t.put(14)
t.put(13)
t.put(4)
t.put(7)
t.put(5)
print(
"""
8
/ \\
3 10
/ \\\\
1 6 14
/ \\ /
4 7 13
\\
5
"""
)
print("Label 6 exists:", t.exists(6))
print("Label 13 exists:", t.exists(13))
print("Label -1 exists:", t.exists(-1))
print("Label 12 exists:", t.exists(12))
# Prints all the elements of the list in inorder traversal
inorder_traversal_nodes= [i.labelforiint.inorder_traversal()]
print("Inorder traversal:", inorder_traversal_nodes)
# Prints all the elements of the list in preorder traversal
preorder_traversal_nodes= [i.labelforiint.preorder_traversal()]
print("Preorder traversal:", preorder_traversal_nodes)
print("Max. label:", t.get_max_label())
print("Min. label:", t.get_min_label())
# Delete elements
print("\nDeleting elements 13, 10, 8, 3, 6, 14")
print(
"""
4
/ \\
1 7
\\
5
"""
)
t.remove(13)
t.remove(10)
t.remove(8)
t.remove(3)
t.remove(6)
t.remove(14)
# Prints all the elements of the list in inorder traversal after delete
inorder_traversal_nodes= [i.labelforiint.inorder_traversal()]
print("Inorder traversal after delete:", inorder_traversal_nodes)
# Prints all the elements of the list in preorder traversal after delete
preorder_traversal_nodes= [i.labelforiint.preorder_traversal()]
print("Preorder traversal after delete:", preorder_traversal_nodes)
print("Max. label:", t.get_max_label())
print("Min. label:", t.get_min_label())
if__name__=="__main__":
binary_search_tree_example()