добавлена реализация дерева
This commit is contained in:
parent
76b52b99e4
commit
e1ad783b49
|
|
@ -65,6 +65,8 @@ def ll_list_all(head):
|
||||||
records.sort(key=lambda x: x[0])
|
records.sort(key=lambda x: x[0])
|
||||||
return records
|
return records
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# 2. Hash Function
|
# 2. Hash Function
|
||||||
|
|
||||||
def hash_function(name, table_size):
|
def hash_function(name, table_size):
|
||||||
|
|
@ -102,3 +104,80 @@ def ht_list_all(buckets):
|
||||||
current = current['next']
|
current = current['next']
|
||||||
records.sort(key=lambda x: x[0])
|
records.sort(key=lambda x: x[0])
|
||||||
return records
|
return records
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#3. Tree function
|
||||||
|
|
||||||
|
|
||||||
|
def bst_insert(root, name, phone):
|
||||||
|
|
||||||
|
if root is None:
|
||||||
|
return {'name': name, 'phone': phone, 'left': None, 'right': None}
|
||||||
|
|
||||||
|
if name < root['name']:
|
||||||
|
root['left'] = bst_insert(root['left'], name, phone)
|
||||||
|
elif name > root['name']:
|
||||||
|
root['right'] = bst_insert(root['right'], name, phone)
|
||||||
|
else:
|
||||||
|
root['phone'] = phone
|
||||||
|
|
||||||
|
return root
|
||||||
|
|
||||||
|
|
||||||
|
def bst_find(root, name):
|
||||||
|
|
||||||
|
current = root
|
||||||
|
while current is not None:
|
||||||
|
if name == current['name']:
|
||||||
|
return current['phone']
|
||||||
|
elif name < current['name']:
|
||||||
|
current = current['left']
|
||||||
|
else:
|
||||||
|
current = current['right']
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def bst_find_min(node):
|
||||||
|
|
||||||
|
current = node
|
||||||
|
while current['left'] is not None:
|
||||||
|
current = current['left']
|
||||||
|
return current
|
||||||
|
|
||||||
|
|
||||||
|
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']
|
||||||
|
elif 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_list_all(root):
|
||||||
|
|
||||||
|
records = []
|
||||||
|
|
||||||
|
def inorder_traversal(node):
|
||||||
|
if node is not None:
|
||||||
|
inorder_traversal(node['left'])
|
||||||
|
records.append((node['name'], node['phone']))
|
||||||
|
inorder_traversal(node['right'])
|
||||||
|
|
||||||
|
inorder_traversal(root)
|
||||||
|
return records
|
||||||
Loading…
Reference in New Issue
Block a user