2026-rff_mp/kuznetsovTD/task1/structures/BinaryTree.py
2026-04-30 23:54:08 +03:00

70 lines
1.7 KiB
Python

def bst_insert(root: dict | None, name: str, phone: str) -> dict:
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: dict | None, name: str) -> str | None:
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 _min_value(node: dict) -> dict:
while node['left'] is not None:
node = node['left']
return node
def bst_delete(root: dict | None, name: str) -> dict | None:
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 = _min_value(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: dict | None) -> list:
result = []
def walk(node: dict | None):
if node is None:
return
walk(node['left'])
result.append((node['name'], node['phone']))
walk(node['right'])
walk(root)
return result