MCPcopy
hub / github.com/keon/algorithms / _remove_key

Method _remove_key

algorithms/data_structures/b_tree.py:159–190  ·  view source on GitHub ↗

Recursively remove a key from the subtree rooted at node. Args: node: The root of the subtree to remove from. key: The key to remove. Returns: True if the key was found and removed, False otherwise.

(self, node: Node, key: int)

Source from the content-addressed store, hash-verified

157 self._remove_key(self.root, key)
158
159 def _remove_key(self, node: Node, key: int) -> bool:
160 """Recursively remove a key from the subtree rooted at node.
161
162 Args:
163 node: The root of the subtree to remove from.
164 key: The key to remove.
165
166 Returns:
167 True if the key was found and removed, False otherwise.
168 """
169 try:
170 key_index = node.keys.index(key)
171 if node.is_leaf:
172 node.keys.remove(key)
173 else:
174 self._remove_from_nonleaf_node(node, key_index)
175 return True
176
177 except ValueError:
178 if node.is_leaf:
179 return False
180 else:
181 i = 0
182 number_of_keys = len(node.keys)
183 while i < number_of_keys and key > node.keys[i]:
184 i += 1
185
186 action_performed = self._repair_tree(node, i)
187 if action_performed:
188 return self._remove_key(node, key)
189 else:
190 return self._remove_key(node.children[i], key)
191
192 def _repair_tree(self, node: Node, child_index: int) -> bool:
193 """Repair the tree after a deletion to maintain B-tree properties.

Callers 2

remove_keyMethod · 0.95

Calls 3

_repair_treeMethod · 0.95
removeMethod · 0.45

Tested by

no test coverage detected