@@ -196,8 +196,13 @@ def get_left_most(root: MyNode) -> Any:
196
196
197
197
198
198
def del_node (root : MyNode , data : Any ) -> MyNode | None :
199
+ if root is None :
200
+ print ("Node is empty, nothing to delete" )
201
+ return None
202
+
199
203
left_child = root .get_left ()
200
204
right_child = root .get_right ()
205
+
201
206
if root .get_data () == data :
202
207
if left_child is not None and right_child is not None :
203
208
temp_data = get_left_most (right_child )
@@ -209,32 +214,41 @@ def del_node(root: MyNode, data: Any) -> MyNode | None:
209
214
root = right_child
210
215
else :
211
216
return None
212
- elif root .get_data () > data :
217
+ elif data < root .get_data ():
213
218
if left_child is None :
214
- print ("No such data" )
219
+ print (f "No such data ( { data } ) exists in the left subtree. " )
215
220
return root
216
221
else :
217
222
root .set_left (del_node (left_child , data ))
218
- # root.get_data() < data
219
- elif right_child is None :
220
- return root
221
223
else :
222
- root .set_right (del_node (right_child , data ))
224
+ if right_child is None :
225
+ print (f"No such data ({ data } ) exists in the right subtree." )
226
+ return root
227
+ else :
228
+ root .set_right (del_node (right_child , data ))
229
+
230
+ # Update the height of the node
231
+ root .set_height (
232
+ 1 + my_max (get_height (root .get_left ()), get_height (root .get_right ()))
233
+ )
223
234
224
- if get_height (right_child ) - get_height (left_child ) == 2 :
235
+ # Get the balance factor
236
+ balance_factor = get_height (root .get_right ()) - get_height (root .get_left ())
237
+
238
+ # Balance the tree
239
+ if balance_factor == 2 :
225
240
assert right_child is not None
226
241
if get_height (right_child .get_right ()) > get_height (right_child .get_left ()):
227
242
root = left_rotation (root )
228
243
else :
229
244
root = rl_rotation (root )
230
- elif get_height ( right_child ) - get_height ( left_child ) == - 2 :
245
+ elif balance_factor == - 2 :
231
246
assert left_child is not None
232
247
if get_height (left_child .get_left ()) > get_height (left_child .get_right ()):
233
248
root = right_rotation (root )
234
249
else :
235
250
root = lr_rotation (root )
236
- height = my_max (get_height (root .get_right ()), get_height (root .get_left ())) + 1
237
- root .set_height (height )
251
+
238
252
return root
239
253
240
254
0 commit comments