MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / Delete

Method Delete

structure/tree/btree.go:244–345  ·  view source on GitHub ↗
(tree *BTree[T], key T)

Source from the content-addressed store, hash-verified

242}
243
244func (node *BTreeNode[T]) Delete(tree *BTree[T], key T) {
245 node.Verify(tree)
246 if node.isLeaf {
247 // Case 1: Node is a leaf. Directly delete the key.
248 for i := 0; i < node.numKeys; i++ {
249 if key == node.keys[i] {
250 node.DeleteIthKey(i)
251 return
252 }
253 }
254 return
255 }
256
257 minKeys := minKeys(tree.maxKeys)
258 i := 0
259 for ; i < node.numKeys; i++ {
260 if key == node.keys[i] {
261 // Case 2: key exists in a non-leaf node
262 left := node.children[i]
263 right := node.children[i+1]
264 if left.numKeys > minKeys {
265 // Replace the key we want to delete with the max key from the left
266 // subtree. Then delete that key from the left subtree.
267 // A B C
268 // /
269 // a b c
270 //
271 // If we want to delete `B`, then replace `B` with `c`, and delete `c` in the subtree.
272 // A c C
273 // /
274 // a b
275 replacementKey := left.Max()
276 node.keys[i] = replacementKey
277 left.Delete(tree, replacementKey)
278 } else if right.numKeys > minKeys {
279 // Replace the key we want to delete with the min key from the right
280 // subtree. Then delete that key in the right subtree. Mirrors the
281 // transformation above for replacing from the left subtree.
282 replacementKey := right.Min()
283 node.keys[i] = replacementKey
284 right.Delete(tree, replacementKey)
285 } else {
286 // Both left and right subtrees have the minimum number of keys. Merge
287 // the left tree, the deleted key, and the right tree together into the
288 // left tree. Then recursively delete the key in the left tree.
289 if left.numKeys != minKeys || right.numKeys != minKeys {
290 panic("nodes should not have less than the minimum number of keys")
291 }
292 node.Merge(i)
293 left.Delete(tree, key)
294 }
295 return
296 }
297
298 if key < node.keys[i] {
299 break
300 }
301 }

Callers

nothing calls this directly

Calls 9

VerifyMethod · 0.95
DeleteIthKeyMethod · 0.95
MergeMethod · 0.95
minKeysFunction · 0.85
InsertKeyChildMethod · 0.80
AppendMethod · 0.80
MaxMethod · 0.65
DeleteMethod · 0.65
MinMethod · 0.65

Tested by

no test coverage detected