83 lines
2.0 KiB
Python
83 lines
2.0 KiB
Python
|
|
def bst_insert(root: dict | None, name: str, phone: str) -> dict:
|
||
|
|
new_node = {'name': name, 'phone': phone, 'left': None, 'right': None}
|
||
|
|
|
||
|
|
if root is None:
|
||
|
|
return new_node
|
||
|
|
|
||
|
|
current = root
|
||
|
|
|
||
|
|
while True:
|
||
|
|
if name == current['name']:
|
||
|
|
current['phone'] = phone
|
||
|
|
return root
|
||
|
|
|
||
|
|
if name < current['name']:
|
||
|
|
if current['left'] is None:
|
||
|
|
current['left'] = new_node
|
||
|
|
return root
|
||
|
|
current = current['left']
|
||
|
|
else:
|
||
|
|
if current['right'] is None:
|
||
|
|
current['right'] = new_node
|
||
|
|
return root
|
||
|
|
current = current['right']
|
||
|
|
|
||
|
|
|
||
|
|
def bst_find(root: dict | None, name: str) -> str | None:
|
||
|
|
current = root
|
||
|
|
|
||
|
|
while current is not None:
|
||
|
|
if name == current['name']:
|
||
|
|
return current['phone']
|
||
|
|
|
||
|
|
if name < current['name']:
|
||
|
|
current = current['left']
|
||
|
|
else:
|
||
|
|
current = current['right']
|
||
|
|
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def bst_min(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 = 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: dict | None) -> list:
|
||
|
|
result = []
|
||
|
|
|
||
|
|
def inorder(node):
|
||
|
|
if node is None:
|
||
|
|
return
|
||
|
|
inorder(node['left'])
|
||
|
|
result.append((node['name'], node['phone']))
|
||
|
|
inorder(node['right'])
|
||
|
|
|
||
|
|
inorder(root)
|
||
|
|
return result
|