@@ -195,61 +195,54 @@ def get_left_most(root: MyNode) -> Any:
195
195
return root .get_data ()
196
196
197
197
198
- # Function to get balance factor
199
198
def get_balance (node : MyNode ) -> int :
200
199
if node is None :
201
200
return 0
202
201
return get_height (node .get_left ()) - get_height (node .get_right ())
203
202
204
-
205
203
def get_min_value_node (node : MyNode ) -> MyNode :
206
204
current = node
207
205
while current .get_left () is not None :
208
206
current = current .get_left ()
209
207
return current
210
208
211
-
212
209
def del_node (root : MyNode , data : Any ) -> MyNode | None :
213
210
if root is None :
214
211
print ("Nothing to delete" )
215
212
return None
216
-
213
+
217
214
if root .get_data () > data :
218
215
root .set_left (del_node (root .get_left (), data ))
219
216
elif root .get_data () < data :
220
217
root .set_right (del_node (root .get_right (), data ))
218
+ elif root .get_left () is None :
219
+ return root .get_right ()
220
+ elif root .get_right () is None :
221
+ return root .get_left ()
221
222
else :
222
- # Node to delete found
223
- if root .get_left () is None :
224
- return root .get_right ()
225
- elif root .get_right () is None :
226
- return root .get_left ()
227
- else :
228
- # Node with two children
229
- temp = get_min_value_node (root .get_right ())
230
- root .set_data (temp .get_data ())
231
- root .set_right (del_node (root .get_right (), temp .get_data ()))
232
-
233
- root .set_height (
234
- 1 + my_max (get_height (root .get_left ()), get_height (root .get_right ()))
235
- )
223
+ # Node with two children
224
+ temp = get_min_value_node (root .get_right ())
225
+ root .set_data (temp .get_data ())
226
+ root .set_right (del_node (root .get_right (), temp .get_data ()))
227
+
228
+ root .set_height (1 + my_max (get_height (root .get_left ()), get_height (root .get_right ())))
236
229
237
230
balance = get_balance (root )
238
231
239
- # Left Left
232
+ # Left Left Case
240
233
if balance > 1 and get_balance (root .get_left ()) >= 0 :
241
234
return right_rotation (root )
242
235
243
- # Left Right
236
+ # Left Right Case
244
237
if balance > 1 and get_balance (root .get_left ()) < 0 :
245
238
root .set_left (left_rotation (root .get_left ()))
246
239
return right_rotation (root )
247
240
248
- # Right Right
241
+ # Right Right Case
249
242
if balance < - 1 and get_balance (root .get_right ()) <= 0 :
250
243
return left_rotation (root )
251
244
252
- # Right Left
245
+ # Right Left Case
253
246
if balance < - 1 and get_balance (root .get_right ()) > 0 :
254
247
root .set_right (right_rotation (root .get_right ()))
255
248
return left_rotation (root )
0 commit comments