[1] Implement binary search tree phonebook

This commit is contained in:
KuznetsovYuM 2026-05-22 17:14:10 +00:00
parent d2001eaf53
commit c009c610a6

View File

@ -52,6 +52,8 @@ def linked_list_collect_all(head):
return records
#HASH
def _hash_bucket_index(key, table_size):
return hash(key) % table_size
@ -88,13 +90,81 @@ def hash_table_collect_all(table):
return all_records
# Quick test
#BST
def _bst_new_node(name, phone):
return {'name': name, 'phone': phone, 'left': None, 'right': None}
def bst_add(root, name, phone):
"""Insert or update. Returns (possibly new) root."""
if root is None:
return _bst_new_node(name, phone)
if name == root['name']:
root['phone'] = phone
elif name < root['name']:
root['left'] = bst_add(root['left'], name, phone)
else:
root['right'] = bst_add(root['right'], name, phone)
return root
def bst_find(root, name):
if root is None:
return None
if name == root['name']:
return root['phone']
elif name < root['name']:
return bst_find(root['left'], name)
else:
return bst_find(root['right'], name)
def _bst_find_minimum(node):
while node['left'] is not None:
node = node['left']
return node
def bst_remove(root, name):
if root is None:
return None
if name < root['name']:
root['left'] = bst_remove(root['left'], name)
elif name > root['name']:
root['right'] = bst_remove(root['right'], name)
else:
if root['left'] is None:
return root['right']
if root['right'] is None:
return root['left']
successor = _bst_find_minimum(root['right'])
root['name'] = successor['name']
root['phone'] = successor['phone']
root['right'] = bst_remove(root['right'], successor['name'])
return root
def bst_collect_inorder(root):
result = []
def inorder(node):
if node is None:
return
inorder(node['left'])
result.append((node['name'], node['phone']))
inorder(node['right'])
inorder(root)
return result
if __name__ == '__main__':
ht = hash_table_create(5)
ht = hash_table_put(ht, 'Alice', '111')
ht = hash_table_put(ht, 'Bob', '222')
ht = hash_table_put(ht, 'Alice', '333')
print(hash_table_get(ht, 'Alice')) # 333
print(hash_table_get(ht, 'Charlie')) # None
ht = hash_table_remove(ht, 'Bob')
print(hash_table_collect_all(ht)) # [('Alice','333')]
tree = None
tree = bst_add(tree, 'Zoe', '111')
tree = bst_add(tree, 'Alice', '222')
tree = bst_add(tree, 'Bob', '333')
tree = bst_add(tree, 'Alice', '444')
print(bst_find(tree, 'Alice')) # 444
tree = bst_remove(tree, 'Bob')
print(bst_collect_inorder(tree)) # [('Alice','444'), ('Zoe','111')]