[2] 2-nd-exercise #268
|
|
@ -85,13 +85,79 @@ def ht_get_all(table):
|
|||
return all_entries
|
||||
|
||||
|
||||
def bst_create_node(name, phone):
|
||||
return {'name': name, 'phone': phone, 'left': None, 'right': None}
|
||||
|
||||
|
||||
def bst_insert(root, name, phone):
|
||||
if root is None:
|
||||
return bst_create_node(name, phone)
|
||||
if name == root['name']:
|
||||
root['phone'] = phone
|
||||
elif name < root['name']:
|
||||
root['left'] = bst_insert(root['left'], name, phone)
|
||||
else:
|
||||
root['right'] = bst_insert(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_min(node):
|
||||
while node['left'] is not None:
|
||||
node = node['left']
|
||||
return node
|
||||
|
||||
|
||||
def bst_delete(root, name):
|
||||
if root is None:
|
||||
return None
|
||||
if name < root['name']:
|
||||
root['left'] = bst_delete(root['left'], name)
|
||||
elif name > root['name']:
|
||||
root['right'] = bst_delete(root['right'], name)
|
||||
else:
|
||||
if root['left'] is None:
|
||||
return root['right']
|
||||
if root['right'] is None:
|
||||
return root['left']
|
||||
min_node = bst_find_min(root['right'])
|
||||
root['name'] = min_node['name']
|
||||
root['phone'] = min_node['phone']
|
||||
root['right'] = bst_delete(root['right'], min_node['name'])
|
||||
return root
|
||||
|
||||
|
||||
def bst_inorder_collect(root, out_list):
|
||||
if root is not None:
|
||||
bst_inorder_collect(root['left'], out_list)
|
||||
out_list.append((root['name'], root['phone']))
|
||||
bst_inorder_collect(root['right'], out_list)
|
||||
|
||||
|
||||
def bst_get_all(root):
|
||||
result = []
|
||||
bst_inorder_collect(root, result)
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
table = ht_create()
|
||||
ht_insert(table, "Alice", "111-222")
|
||||
ht_insert(table, "Bob", "333-444")
|
||||
ht_insert(table, "Alice", "555-666")
|
||||
print(ht_find(table, "Alice"))
|
||||
print(ht_find(table, "Bob"))
|
||||
print(ht_find(table, "Charlie"))
|
||||
ht_delete(table, "Bob")
|
||||
print(ht_get_all(table))
|
||||
root = None
|
||||
root = bst_insert(root, "Charlie", "111-111")
|
||||
root = bst_insert(root, "Alice", "222-222")
|
||||
root = bst_insert(root, "Bob", "333-333")
|
||||
root = bst_insert(root, "Alice", "444-444")
|
||||
print(bst_find(root, "Alice"))
|
||||
print(bst_find(root, "Bob"))
|
||||
print(bst_get_all(root))
|
||||
root = bst_delete(root, "Bob")
|
||||
print(bst_get_all(root))
|
||||
Loading…
Reference in New Issue
Block a user