Algorithms and Data Structures with PythonChapter 102
Adding Search Functionality
Section 2 of 5-~ 12 min read-Synced from Cuantum content
One of the key features of any contact book is the ability to search for a contact. We will implement a search functionality using binary search within our BST structure.
Binary Search in BST for Contact Retrieval:
Here’s how we can implement the search functionality:
class ContactBookBST: # ... previous methods ... def search(self, root, name): if root is None or root.name == name: return root if name < root.name: return self.search(root.left, name) return self.search(root.right, name) def find_contact(self, name): return self.search(self.root, name) # Example Usagecontact = contact_book.find_contact("Alice")if contact: print(f"Contact Found: {contact.name}, {contact.phone}, {contact.email}")else: print("Contact not found.")In this method, find_contact initiates a search for a contact by name, traversing the BST according to the binary search principle.