Skip to content

Fix removing the root node in binary_search_tree.py removes the whole tree #8819

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
20 changes: 17 additions & 3 deletions data_structures/binary_tree/binary_search_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,14 @@ def __str__(self) -> str:
def __reassign_nodes(self, node: Node, new_children: Node | None) -> None:
if new_children is not None: # reset its kids
new_children.parent = node.parent
if node.parent is not None: # reset its parent
if (
node == self.root
): # This check if the node is the head and assign the root to the remaining
Comment on lines +37 to +39
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please do not wrap line for a comment.

Suggested change
if (
node == self.root
): # This check if the node is the head and assign the root to the remaining
# This check if the node is the head and assigns the root to the remaining
if node == self.root:

if self.is_right(node): # If it is the right children
self.root = new_children
else:
self.root = new_children
Comment on lines +40 to +43
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why execute the if statement when the code executed is identical either way?

elif node.parent is not None: # reset its parent
if self.is_right(node): # If it is the right children
node.parent.right = new_children
else:
Expand Down Expand Up @@ -194,6 +201,15 @@ def binary_search_tree() -> None:
8 3 1 6 4 7 10 14 13
>>> print(" ".join(repr(i.value) for i in t.traversal_tree(postorder)))
1 4 7 6 3 13 14 10 8
>>> t.remove(10)
>>> print(" ".join(repr(i.value) for i in t.traversal_tree()))
8 3 1 6 4 7 14 13
>>> t.remove(8)
>>> print(" ".join(repr(i.value) for i in t.traversal_tree()))
7 3 1 6 4 14 13
>>> t.remove(14)
>>> print(" ".join(repr(i.value) for i in t.traversal_tree()))
7 3 1 6 4 13
>>> BinarySearchTree().search(6)
Traceback (most recent call last):
...
Expand All @@ -203,10 +219,8 @@ def binary_search_tree() -> None:
t = BinarySearchTree()
for i in testlist:
t.insert(i)

# Prints all the elements of the list in order traversal
print(t)

if t.search(6) is not None:
print("The value 6 exists")
else:
Expand Down