1
0
forked from UNN/2026-rff_mp
2026-rff_mp/KorotkinSE/task1/bst.py
2026-09-23 11:53:32 +03:00

88 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class BSTNode:
def __init__(self, name, phone):
self.name = name
self.phone = phone
self.left = None
self.right = None
def bst_insert(root, name, phone):
"""Итеративная вставка в BST (защита от RecursionError)"""
new_node = BSTNode(name, phone)
if root is None:
return new_node
current = root
while True:
if name < current.name:
if current.left is None:
current.left = new_node
break
current = current.left
elif name > current.name:
if current.right is None:
current.right = new_node
break
current = current.right
else:
current.phone = phone
break
return root
def bst_find(root, name):
"""Итеративный поиск в BST"""
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 bst_find_min(root):
"""Поиск минимального узла в поддереве"""
current = root
while current.left is not None:
current = current.left
return current
def bst_delete(root, name):
"""Рекурсивное удаление из BST"""
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
else:
# Узел с двумя потомками: ищем минимального в правом поддереве
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=None):
"""Обход дерева In-Order (результат будет отсортирован по имени)"""
if records is None:
records = []
stack = []
current = root
while stack or current:
while current is not None:
stack.append(current)
current = current.left
current = stack.pop()
records.append((current.name, current.phone))
current = current.right
return records