From dd054c4034e53c664b15f5b467df738584533918 Mon Sep 17 00:00:00 2001 From: Sorokin Fedor Date: Tue, 19 May 2026 18:26:19 +0300 Subject: [PATCH] =?UTF-8?q?=D0=B7=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=201:?= =?UTF-8?q?=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB=20=D0=B4=D0=B2?= =?UTF-8?q?=D0=BE=D0=B8=D1=87=D0=BD=D0=BE=D0=B5=20=D0=B4=D0=B5=D1=80=D0=B5?= =?UTF-8?q?=D0=B2=D0=BE=20=D0=BF=D0=BE=D0=B8=D1=81=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sorokinfi/427.md | 67 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/sorokinfi/427.md b/sorokinfi/427.md index 64259e8..04adbd1 100644 --- a/sorokinfi/427.md +++ b/sorokinfi/427.md @@ -89,4 +89,69 @@ def ht_list_all(buckets): all_records.append((current['name'], current['phone'])) current = current['next'] all_records.sort(key=lambda x: x[0]) - return all_records \ No newline at end of file + return all_records + + +# 3. двоичное дерево поиска +# узел — словарь: {'name': 'Имя', 'phone': '123', 'left': None, 'right': None} + +# рекурсивно или итеративно вставляет, возвращает новый корень (если корень меняется) +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_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'] + # две ветви + successor = root['right'] + while successor['left'] is not None: + successor = successor['left'] + + root['name'] = successor['name'] + root['phone'] = successor['phone'] + root['right'] = bst_delete(root['right'], successor['name']) + + return root + +# центрированный обход (рекурсивно собирает записи в отсортированном порядке) +def bst_list_all(root): + records = [] + def _inorder(node): + if node is not None: + _inorder(node['left']) + records.append((node['name'], node['phone'])) + _inorder(node['right']) + _inorder(root) + return records \ No newline at end of file