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.py
More file actions
Latest commit
356 lines (308 loc) · 10.7 KB
/
Copy pathbinary_search_tree.py
File metadata and controls
356 lines (308 loc) · 10.7 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
r"""
A binary search Tree
Example
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
>>> t = BinarySearchTree().insert(8, 3, 6, 1, 10, 14, 13, 4, 7)
>>> print(" ".join(repr(i.value) for i in t.traversal_tree()))
8 3 1 6 4 7 10 14 13
>>> tuple(i.value for i in t.traversal_tree(inorder))
(1, 3, 4, 6, 7, 8, 10, 13, 14)
>>> tuple(t)
(1, 3, 4, 6, 7, 8, 10, 13, 14)
>>> t.find_kth_smallest(3, t.root)
4
>>> tuple(t)[3-1]
4
>>> print(" ".join(repr(i.value) for i in t.traversal_tree(postorder)))
1 4 7 6 3 13 14 10 8
>>> t.remove(20)
Traceback (most recent call last):
...
ValueError: Value 20 not found
>>> BinarySearchTree().search(6)
Traceback (most recent call last):
...
IndexError: Warning: Tree is empty! please use another.
Other example:
>>> testlist = (8, 3, 6, 1, 10, 14, 13, 4, 7)
>>> t = BinarySearchTree()
>>> for i in testlist:
... t.insert(i) # doctest: +ELLIPSIS
BinarySearchTree(root=8)
BinarySearchTree(root={'8': (3, None)})
BinarySearchTree(root={'8': ({'3': (None, 6)}, None)})
BinarySearchTree(root={'8': ({'3': (1, 6)}, None)})
BinarySearchTree(root={'8': ({'3': (1, 6)}, 10)})
BinarySearchTree(root={'8': ({'3': (1, 6)}, {'10': (None, 14)})})
BinarySearchTree(root={'8': ({'3': (1, 6)}, {'10': (None, {'14': (13, None)})})})
BinarySearchTree(root={'8': ({'3': (1, {'6': (4, None)})}, {'10': (None, {'14': ...
BinarySearchTree(root={'8': ({'3': (1, {'6': (4, 7)})}, {'10': (None, {'14': (13, ...
Prints all the elements of the list in order traversal
>>> print(t)
{'8': ({'3': (1, {'6': (4, 7)})}, {'10': (None, {'14': (13, None)})})}
Test existence
>>> t.search(6) is not None
True
>>> 6 in t
True
>>> t.search(-1) is not None
False
>>> -1 in t
False
>>> t.search(6).is_right
True
>>> t.search(1).is_right
False
>>> t.get_max().value
14
>>> max(t)
14
>>> t.get_min().value
1
>>> min(t)
1
>>> t.empty()
False
>>> not t
False
>>> for i in testlist:
... t.remove(i)
>>> t.empty()
True
>>> not t
True
"""
from __future__ importannotations
fromcollections.abcimportIterable, Iterator
fromdataclassesimportdataclass
fromtypingimportAny, Self
@dataclass
classNode:
value: int
left: Node|None=None
right: Node|None=None
parent: Node|None=None# Added in order to delete a node easier
def__iter__(self) ->Iterator[int]:
"""
>>> list(Node(0))
[0]
>>> list(Node(0, Node(-1), Node(1), None))
[-1, 0, 1]
"""
yieldfromself.leftor []
yieldself.value
yieldfromself.rightor []
def__repr__(self) ->str:
frompprintimportpformat
ifself.leftisNoneandself.rightisNone:
returnstr(self.value)
returnpformat({f"{self.value}": (self.left, self.right)}, indent=1)
@property
defis_right(self) ->bool:
returnbool(self.parentandselfisself.parent.right)
@dataclass
classBinarySearchTree:
root: Node|None=None
def__bool__(self) ->bool:
returnbool(self.root)
def__iter__(self) ->Iterator[int]:
yieldfromself.rootor []
def__str__(self) ->str:
"""
Return a string of all the Nodes using in order traversal
"""
returnstr(self.root)
def__reassign_nodes(self, node: Node, new_children: Node|None) ->None:
ifnew_childrenisnotNone: # reset its kids
new_children.parent=node.parent
ifnode.parentisnotNone: # reset its parent
ifnode.is_right: # If it is the right child
node.parent.right=new_children
else:
node.parent.left=new_children
else:
self.root=new_children
defempty(self) ->bool:
"""
Returns True if the tree does not have any element(s).
False if the tree has element(s).
>>> BinarySearchTree().empty()
True
>>> BinarySearchTree().insert(1).empty()
False
>>> BinarySearchTree().insert(8, 3, 6, 1, 10, 14, 13, 4, 7).empty()
False
"""
returnnotself.root
def__insert(self, value) ->None:
"""
Insert a new node in Binary Search Tree with value label
"""
new_node=Node(value) # create a new Node
ifself.empty(): # if Tree is empty
self.root=new_node# set its root
else: # Tree is not empty
parent_node=self.root# from root
ifparent_nodeisNone:
return
whileTrue: # While we don't get to a leaf
ifvalue<parent_node.value: # We go left
ifparent_node.leftisNone:
parent_node.left=new_node# We insert the new node in a leaf
break
else:
parent_node=parent_node.left
elifparent_node.rightisNone:
parent_node.right=new_node
break
else:
parent_node=parent_node.right
new_node.parent=parent_node
definsert(self, *values) ->Self:
forvalueinvalues:
self.__insert(value)
returnself
defsearch(self, value) ->Node|None:
"""
>>> tree = BinarySearchTree().insert(10, 20, 30, 40, 50)
>>> tree.search(10)
{'10': (None, {'20': (None, {'30': (None, {'40': (None, 50)})})})}
>>> tree.search(20)
{'20': (None, {'30': (None, {'40': (None, 50)})})}
>>> tree.search(30)
{'30': (None, {'40': (None, 50)})}
>>> tree.search(40)
{'40': (None, 50)}
>>> tree.search(50)
50
>>> tree.search(5) is None # element not present
True
>>> tree.search(0) is None # element not present
True
>>> tree.search(-5) is None # element not present
True
>>> BinarySearchTree().search(10)
Traceback (most recent call last):
...
IndexError: Warning: Tree is empty! please use another.
"""
ifself.empty():
raiseIndexError("Warning: Tree is empty! please use another.")
else:
node=self.root
# use lazy evaluation here to avoid NoneType Attribute error
whilenodeisnotNoneandnode.valueisnotvalue:
node=node.leftifvalue<node.valueelsenode.right
returnnode
defget_max(self, node: Node|None=None) ->Node|None:
"""
We go deep on the right branch
>>> BinarySearchTree().insert(10, 20, 30, 40, 50).get_max()
50
>>> BinarySearchTree().insert(-5, -1, 0.1, -0.3, -4.5).get_max()
{'0.1': (-0.3, None)}
>>> BinarySearchTree().insert(1, 78.3, 30, 74.0, 1).get_max()
{'78.3': ({'30': (1, 74.0)}, None)}
>>> BinarySearchTree().insert(1, 783, 30, 740, 1).get_max()
{'783': ({'30': (1, 740)}, None)}
"""
ifnodeisNone:
ifself.rootisNone:
returnNone
node=self.root
ifnotself.empty():
whilenode.rightisnotNone:
node=node.right
returnnode
defget_min(self, node: Node|None=None) ->Node|None:
"""
We go deep on the left branch
>>> BinarySearchTree().insert(10, 20, 30, 40, 50).get_min()
{'10': (None, {'20': (None, {'30': (None, {'40': (None, 50)})})})}
>>> BinarySearchTree().insert(-5, -1, 0, -0.3, -4.5).get_min()
{'-5': (None, {'-1': (-4.5, {'0': (-0.3, None)})})}
>>> BinarySearchTree().insert(1, 78.3, 30, 74.0, 1).get_min()
{'1': (None, {'78.3': ({'30': (1, 74.0)}, None)})}
>>> BinarySearchTree().insert(1, 783, 30, 740, 1).get_min()
{'1': (None, {'783': ({'30': (1, 740)}, None)})}
"""
ifnodeisNone:
node=self.root
ifself.rootisNone:
returnNone
ifnotself.empty():
node=self.root
whilenode.leftisnotNone:
node=node.left
returnnode
defremove(self, value: int) ->None:
# Look for the node with that label
node=self.search(value)
ifnodeisNone:
msg=f"Value {value} not found"
raiseValueError(msg)
ifnode.leftisNoneandnode.rightisNone: # If it has no children
self.__reassign_nodes(node, None)
elifnode.leftisNone: # Has only right children
self.__reassign_nodes(node, node.right)
elifnode.rightisNone: # Has only left children
self.__reassign_nodes(node, node.left)
else:
predecessor=self.get_max(
node.left
) # Gets the max value of the left branch
self.remove(predecessor.value) # type: ignore[union-attr]
node.value= (
predecessor.value# type: ignore[union-attr]
) # Assigns the value to the node to delete and keep tree structure
defpreorder_traverse(self, node: Node|None) ->Iterable:
ifnodeisnotNone:
yieldnode# Preorder Traversal
yieldfromself.preorder_traverse(node.left)
yieldfromself.preorder_traverse(node.right)
deftraversal_tree(self, traversal_function=None) ->Any:
"""
This function traversal the tree.
You can pass a function to traversal the tree as needed by client code
"""
iftraversal_functionisNone:
returnself.preorder_traverse(self.root)
else:
returntraversal_function(self.root)
definorder(self, arr: list, node: Node|None) ->None:
"""Perform an inorder traversal and append values of the nodes to
a list named arr"""
ifnode:
self.inorder(arr, node.left)
arr.append(node.value)
self.inorder(arr, node.right)
deffind_kth_smallest(self, k: int, node: Node) ->int:
"""Return the kth smallest element in a binary search tree"""
arr: list[int] = []
self.inorder(arr, node) # append all values to list using inorder traversal
returnarr[k-1]
definorder(curr_node: Node|None) ->list[Node]:
"""
inorder (left, self, right)
"""
node_list= []
ifcurr_nodeisnotNone:
node_list= [*inorder(curr_node.left), curr_node, *inorder(curr_node.right)]
returnnode_list
defpostorder(curr_node: Node|None) ->list[Node]:
"""
postOrder (left, right, self)
"""
node_list= []
ifcurr_nodeisnotNone:
node_list=postorder(curr_node.left) +postorder(curr_node.right) + [curr_node]
returnnode_list
if__name__=="__main__":
importdoctest
doctest.testmod(verbose=True)