66 lines
1.7 KiB
Python
66 lines
1.7 KiB
Python
def create_bst_node(name, phone):
|
|
return {'name': name, 'phone': phone, 'left': None, 'right': None}
|
|
|
|
def bst_insert(root, name, phone):
|
|
if root is None:
|
|
return create_bst_node(name, phone)
|
|
|
|
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 bst_find(root['left'], name)
|
|
elif name > root['name']:
|
|
return bst_find(root['right'], name)
|
|
else:
|
|
return root['phone']
|
|
|
|
def bst_find_min(root):
|
|
current = root
|
|
while current and current['left'] is not None:
|
|
current = current['left']
|
|
return current
|
|
|
|
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']
|
|
elif root['right'] is None:
|
|
return root['left']
|
|
|
|
min_node = bst_find_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 = []
|
|
|
|
def inorder_traversal(node):
|
|
if node is None:
|
|
return
|
|
inorder_traversal(node['left'])
|
|
records.append((node['name'], node['phone']))
|
|
inorder_traversal(node['right'])
|
|
|
|
inorder_traversal(root)
|
|
return records |