Compare commits

..

5 commits

Author SHA1 Message Date
Bruno BELANYI 691cf704f4 Add Treap Revisited post
Some checks failed
ci/woodpecker/push/deploy/2 Pipeline failed
ci/woodpecker/cron/deploy/2 Pipeline failed
2024-07-27 18:41:07 +01:00
Bruno BELANYI aa72b269c2 posts: treap: add removal 2024-07-27 18:41:07 +01:00
Bruno BELANYI eaaa9c9ae2 posts: treap-revisited: add insertion 2024-07-27 18:41:07 +01:00
Bruno BELANYI b3ed39eef3 posts: treap: add merge 2024-07-27 18:41:07 +01:00
Bruno BELANYI aee1fa55c8 posts: treap-revisited: add split 2024-07-27 18:41:07 +01:00

View file

@ -48,27 +48,29 @@ Splitting a tree means taking a key, and getting the following output:
```python ```python
type OptionalNode[K, V] = Node[K, V] | None type OptionalNode[K, V] = Node[K, V] | None
def split( class SplitResult(NamedTuple):
root: OptionalNode[K, V], left: OptionalNode
key: K, node: OptionalNode
) -> tuple[OptionalNode[K, V], OptionalNode[K, V], OptionalNode[K, V]]: right: OptionalNode
def split(root: OptionalNode[K, V], key: K) -> SplitResult:
# Base case, empty tree # Base case, empty tree
if root is None: if root is None:
return None, None, None return SplitResult(None, None, None)
# If we found the key, simply extract left and right # If we found the key, simply extract left and right
if root.key == key: if root.key == key:
left, right = root.left, root.right left, right = root.left, root.right
root.left, root.right = None, None root.left, root.right = None, None
return left, root, right return SplitResult(left, root, right)
# Otherwise, recurse on the corresponding side of the tree # Otherwise, recurse on the corresponding side of the tree
if root.key < key: if root.key < key:
left, node, right = split(root.right, key) left, node, right = split(root.right, key)
root.right = left root.right = left
return root, node, right return SplitResult(root, node, right)
if key < root.key: if key < root.key:
left, node, right = split(root.left, key) left, node, right = split(root.left, key)
root.left = right root.left = right
return left, node, root return SplitResult(left, node, root)
raise RuntimeError("Unreachable") raise RuntimeError("Unreachable")
``` ```