Skip to content

Improved del_node function in avl_tree.py #12009

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 24 additions & 10 deletions data_structures/binary_tree/avl_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,13 @@


def del_node(root: MyNode, data: Any) -> MyNode | None:
if root is None:
print("Node is empty, nothing to delete")
return None

left_child = root.get_left()
right_child = root.get_right()

if root.get_data() == data:
if left_child is not None and right_child is not None:
temp_data = get_left_most(right_child)
Expand All @@ -209,32 +214,41 @@
root = right_child
else:
return None
elif root.get_data() > data:
elif data < root.get_data():
if left_child is None:
print("No such data")
print(f"No such data ({data}) exists in the left subtree.")
return root
else:
root.set_left(del_node(left_child, data))
# root.get_data() < data
elif right_child is None:
return root
else:
root.set_right(del_node(right_child, data))
if right_child is None:

Check failure on line 224 in data_structures/binary_tree/avl_tree.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (PLR5501)

data_structures/binary_tree/avl_tree.py:223:5: PLR5501 Use `elif` instead of `else` then `if`, to reduce indentation
print(f"No such data ({data}) exists in the right subtree.")
return root
else:
root.set_right(del_node(right_child, data))

# Update the height of the node
root.set_height(
1 + my_max(get_height(root.get_left()), get_height(root.get_right()))
)

if get_height(right_child) - get_height(left_child) == 2:
# Get the balance factor
balance_factor = get_height(root.get_right()) - get_height(root.get_left())

# Balance the tree
if balance_factor == 2:
assert right_child is not None
if get_height(right_child.get_right()) > get_height(right_child.get_left()):
root = left_rotation(root)
else:
root = rl_rotation(root)
elif get_height(right_child) - get_height(left_child) == -2:
elif balance_factor == -2:
assert left_child is not None
if get_height(left_child.get_left()) > get_height(left_child.get_right()):
root = right_rotation(root)
else:
root = lr_rotation(root)
height = my_max(get_height(root.get_right()), get_height(root.get_left())) + 1
root.set_height(height)

return root


Expand Down
Loading