Algorithms and Data Structures with PythonChapter 101

Adding Delete Functionality

Section 1 of 5-~ 12 min read-Synced from Cuantum content

Another essential functionality is the ability to delete a contact. Deleting a node from a BST requires careful consideration, especially if the node has two children.

Deleting a Node from BST:

Here’s how we can add deletion functionality:

class ContactBookBST:    # ... previous methods ...     def delete_contact_util(self, root, name):        if root is None:            return root        if name < root.name:            root.left = self.delete_contact_util(root.left, name)        elif name > root.name:            root.right = self.delete_contact_util(root.right, name)        else:            if root.left is None:                return root.right            elif root.right is None:                return root.left             temp_val = self.min_value_node(root.right)            root.name = temp_val.name            root.right = self.delete_contact_util(root.right, temp_val.name)         return root     def min_value_node(self, node):        current = node        while current.left is not None:            current = current.left        return current     def delete_contact(self, name):        self.root = self.delete_contact_util(self.root, name) # Example Usagecontact_book.delete_contact("Bob")

This method handles different scenarios such as deleting a node with no children, one child, or two children.