Skip to content

Commit 4a13d5d

Browse files
committed
Test error when deleting non-existing element
1 parent 45c6818 commit 4a13d5d

File tree

1 file changed

+23
-16
lines changed

1 file changed

+23
-16
lines changed

data_structures/binary_tree/binary_search_tree.py

+23-16
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@
1616
8 3 1 6 4 7 10 14 13
1717
>>> print(" ".join(repr(i.value) for i in t.traversal_tree(postorder)))
1818
1 4 7 6 3 13 14 10 8
19+
>>> t.remove(20)
20+
Traceback (most recent call last):
21+
...
22+
ValueError: Value 20 not found
1923
>>> BinarySearchTree().search(6)
2024
Traceback (most recent call last):
2125
...
@@ -173,22 +177,25 @@ def get_min(self, node: Node | None = None) -> Node | None:
173177
return node
174178

175179
def remove(self, value: int) -> None:
176-
node = self.search(value) # Look for the node with that label
177-
if node is not None:
178-
if node.left is None and node.right is None: # If it has no children
179-
self.__reassign_nodes(node, None)
180-
elif node.left is None: # Has only right children
181-
self.__reassign_nodes(node, node.right)
182-
elif node.right is None: # Has only left children
183-
self.__reassign_nodes(node, node.left)
184-
else:
185-
predecessor = self.get_max(
186-
node.left
187-
) # Gets the max value of the left branch
188-
self.remove(predecessor.value) # type: ignore
189-
node.value = (
190-
predecessor.value # type: ignore
191-
) # Assigns the value to the node to delete and keep tree structure
180+
# Look for the node with that label
181+
node = self.search(value)
182+
if node is None:
183+
raise ValueError(f"Value {value} not found")
184+
185+
if node.left is None and node.right is None: # If it has no children
186+
self.__reassign_nodes(node, None)
187+
elif node.left is None: # Has only right children
188+
self.__reassign_nodes(node, node.right)
189+
elif node.right is None: # Has only left children
190+
self.__reassign_nodes(node, node.left)
191+
else:
192+
predecessor = self.get_max(
193+
node.left
194+
) # Gets the max value of the left branch
195+
self.remove(predecessor.value) # type: ignore
196+
node.value = (
197+
predecessor.value # type: ignore
198+
) # Assigns the value to the node to delete and keep tree structure
192199

193200
def preorder_traverse(self, node: Node | None) -> Iterable:
194201
if node is not None:

0 commit comments

Comments
 (0)