Двоичное дерево

This commit is contained in:
Alexander 2026-05-24 23:59:11 +03:00
parent 41433c287a
commit e435c7fcc1

View File

@ -72,4 +72,55 @@ def ht_list_all(table):
while current: while current:
records.append((current['name'], current['phone'])) records.append((current['name'], current['phone']))
current = current['next'] current = current['next']
return sorted(records, key=lambda x: x[0]) return sorted(records, key=lambda x: x[0])
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']
elif name < root['name']:
return bst_find(root['left'], name)
else:
return bst_find(root['right'], name)
def bst_min(node):
while node and node['left']:
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_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 = []
if root:
records.extend(bst_list_all(root['left']))
records.append((root['name'], root['phone']))
records.extend(bst_list_all(root['right']))
return records