Skip to content

Commit b3ba109

Browse files
committed
2 parents c7c39d0 + c91f6b6 commit b3ba109

File tree

1 file changed

+24
-10
lines changed

1 file changed

+24
-10
lines changed

data_structures/binary_tree/avl_tree.py

+24-10
Original file line numberDiff line numberDiff line change
@@ -196,8 +196,13 @@ def get_left_most(root: MyNode) -> Any:
196196

197197

198198
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+
199203
left_child = root.get_left()
200204
right_child = root.get_right()
205+
201206
if root.get_data() == data:
202207
if left_child is not None and right_child is not None:
203208
temp_data = get_left_most(right_child)
@@ -209,32 +214,41 @@ def del_node(root: MyNode, data: Any) -> MyNode | None:
209214
root = right_child
210215
else:
211216
return None
212-
elif root.get_data() > data:
217+
elif data < root.get_data():
213218
if left_child is None:
214-
print("No such data")
219+
print(f"No such data ({data}) exists in the left subtree.")
215220
return root
216221
else:
217222
root.set_left(del_node(left_child, data))
218-
# root.get_data() < data
219-
elif right_child is None:
220-
return root
221223
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+
)
223234

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:
225240
assert right_child is not None
226241
if get_height(right_child.get_right()) > get_height(right_child.get_left()):
227242
root = left_rotation(root)
228243
else:
229244
root = rl_rotation(root)
230-
elif get_height(right_child) - get_height(left_child) == -2:
245+
elif balance_factor == -2:
231246
assert left_child is not None
232247
if get_height(left_child.get_left()) > get_height(left_child.get_right()):
233248
root = right_rotation(root)
234249
else:
235250
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+
238252
return root
239253

240254

0 commit comments

Comments
 (0)