From 883f0e7e9b08d11303f2a8a678a5929bd4c38be5 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sat, 27 Jul 2024 18:33:05 +0100 Subject: [PATCH] posts: treap: add removal --- .../posts/2024-07-27-treap-revisited/index.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/content/posts/2024-07-27-treap-revisited/index.md b/content/posts/2024-07-27-treap-revisited/index.md index 068811f..99ae68f 100644 --- a/content/posts/2024-07-27-treap-revisited/index.md +++ b/content/posts/2024-07-27-treap-revisited/index.md @@ -128,3 +128,19 @@ def insert(self, key: K, value: V) -> bool: # Signal whether the key was already in the key return was_updated ``` + +### Removal + +Removing a key from the tree is similar to inserting a new key, and forgetting +to insert it back: simply `split` the tree and `merge` it back without the +extracted middle node. + +```python +def remove(self, key: K) -> bool: + # `node` contains the key, or `None` if the key wasn't in the tree + left, node, right = split(self._root, key) + # Put the tree back together, without the extract node + self._root = merge(left, right) + # Signal whether `key` was mapped in the tree + return node is not None +```