forked from UNN/2026-rff_mp
implemented bst
This commit is contained in:
parent
fb36061d9a
commit
77485a5318
|
|
@ -89,3 +89,76 @@ def ht_list_all(buckets):
|
|||
result.extend(ll_list_all(head))
|
||||
result.sort(key=lambda x: x[0])
|
||||
return result
|
||||
|
||||
# 3. ДВОИЧНОЕ ДЕРЕВО ПОИСКА (BST)
|
||||
|
||||
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):
|
||||
"""Вернуть телефон или None."""
|
||||
while root is not None:
|
||||
if name == root['name']:
|
||||
return root['phone']
|
||||
elif name < root['name']:
|
||||
root = root['left']
|
||||
else:
|
||||
root = root['right']
|
||||
return None
|
||||
|
||||
|
||||
def _bst_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']
|
||||
# Два потомка: заменить минимальным из правого поддерева
|
||||
successor = _bst_min(root['right'])
|
||||
root['name'] = successor['name']
|
||||
root['phone'] = successor['phone']
|
||||
root['right'] = bst_delete(root['right'], successor['name'])
|
||||
return root
|
||||
|
||||
|
||||
def bst_list_all(root):
|
||||
"""Центрированный (in-order) обход → отсортированный список."""
|
||||
result = []
|
||||
stack = []
|
||||
node = root
|
||||
while stack or node is not None:
|
||||
while node is not None:
|
||||
stack.append(node)
|
||||
node = node['left']
|
||||
node = stack.pop()
|
||||
result.append((node['name'], node['phone']))
|
||||
node = node['right']
|
||||
return result
|
||||
Loading…
Reference in New Issue
Block a user