71 lines
1.9 KiB
Python
71 lines
1.9 KiB
Python
|
|
#Узел — словарь: {'name': 'Имя', 'phone': '123', 'left': None, 'right': None}.
|
||
|
|
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):
|
||
|
|
if root is None:
|
||
|
|
return None
|
||
|
|
|
||
|
|
if name == root['name']:
|
||
|
|
return root['phone']
|
||
|
|
|
||
|
|
if name < root['name']:
|
||
|
|
return bst_find(root['left'], name)
|
||
|
|
|
||
|
|
return bst_find(root['right'], name)
|
||
|
|
|
||
|
|
|
||
|
|
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 = root['right']
|
||
|
|
while min_node['left'] is not None:
|
||
|
|
min_node = min_node['left']
|
||
|
|
|
||
|
|
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):
|
||
|
|
# центрированный обход (рекурсивно собирает записи в отсортированном порядке).
|
||
|
|
if root is None:
|
||
|
|
return []
|
||
|
|
|
||
|
|
return (
|
||
|
|
bst_list_all(root['left']) +
|
||
|
|
[(root['name'], root['phone'])] +
|
||
|
|
bst_list_all(root['right'])
|
||
|
|
)
|