Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 0622d4b

Browse files
committedOct 13, 2024·
Improved del_node(8)
1 parent 4f604e3 commit 0622d4b

File tree

1 file changed

+29
-22
lines changed

1 file changed

+29
-22
lines changed
 

‎data_structures/binary_tree/avl_tree.py

Lines changed: 29 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -219,39 +219,46 @@ def del_node(root: MyNode | None, data: Any) -> MyNode | None:
219219
root.set_left(del_node(root.get_left(), data))
220220
elif root.get_data() < data:
221221
root.set_right(del_node(root.get_right(), data))
222-
elif root.get_left() is None:
223-
return root.get_right()
224-
elif root.get_right() is None:
225-
return root.get_left()
226222
else:
227-
# Node with two children
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+
228228
temp = get_min_value_node(root.get_right())
229+
assert temp is not None
229230
root.set_data(temp.get_data())
230231
root.set_right(del_node(root.get_right(), temp.get_data()))
231232

232-
root.set_height(
233-
1 + my_max(get_height(root.get_left()), get_height(root.get_right()))
234-
)
233+
root.set_height(1 + my_max(get_height(root.get_left()), get_height(root.get_right())))
235234

236235
balance = get_balance(root)
237236

238-
# Left Left Case
239-
if balance > 1 and get_balance(root.get_left()) >= 0:
240-
return right_rotation(root)
237+
if balance > 1:
238+
left_child = root.get_left()
239+
assert left_child is not None
240+
if get_balance(left_child) >= 0:
241+
return right_rotation(root)
241242

242-
# Left Right Case
243-
if balance > 1 and get_balance(root.get_left()) < 0:
244-
root.set_left(left_rotation(root.get_left()))
245-
return right_rotation(root)
243+
if balance > 1:
244+
left_child = root.get_left()
245+
assert left_child is not None
246+
if get_balance(left_child) < 0:
247+
root.set_left(left_rotation(left_child))
248+
return right_rotation(root)
246249

247-
# Right Right Case
248-
if balance < -1 and get_balance(root.get_right()) <= 0:
249-
return left_rotation(root)
250+
if balance < -1:
251+
right_child = root.get_right()
252+
assert right_child is not None
253+
if get_balance(right_child) <= 0:
254+
return left_rotation(root)
250255

251-
# Right Left Case
252-
if balance < -1 and get_balance(root.get_right()) > 0:
253-
root.set_right(right_rotation(root.get_right()))
254-
return left_rotation(root)
256+
if balance < -1:
257+
right_child = root.get_right()
258+
assert right_child is not None
259+
if get_balance(right_child) > 0:
260+
root.set_right(right_rotation(right_child))
261+
return left_rotation(root)
255262

256263
return root
257264

0 commit comments

Comments
 (0)
Please sign in to comment.