From 7cbbdcad069538e49161e00b7f1d83dca4c7e56d Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sat, 27 Jul 2024 18:32:28 +0100 Subject: [PATCH] posts: treap: add merge --- .../posts/2024-07-27-treap-revisited/index.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/content/posts/2024-07-27-treap-revisited/index.md b/content/posts/2024-07-27-treap-revisited/index.md index 3a4d3e6..19e62d6 100644 --- a/content/posts/2024-07-27-treap-revisited/index.md +++ b/content/posts/2024-07-27-treap-revisited/index.md @@ -71,3 +71,33 @@ def split( return left, node, root raise RuntimeError("Unreachable") ``` + +### Merge + +Merging a `left` and `right` tree means (cheaply) building a new tree containing +both of them. A pre-condition for merging is that the `left` tree is composed +entirely of nodes that are lower than any key in `right` (i.e: as in `left` and +`right` after a `split`). + +```python +def merge( + left: OptionalNode[K, V], + right: OptionalNode[K, V], +) -> OptionalNode[K, V]: + # Base cases, left or right being empty + if left is None: + return right + if right is None: + return left + # Left has higher priority, it must become the root node + if left.priority >= right.priority: + # We recursively reconstruct its right sub-tree + left.right = merge(left.right, right) + return left + # Right has higher priority, it must become the root node + if left.priority < right.priority: + # We recursively reconstruct its left sub-tree + right.left = merge(left, right.left) + return right + raise RuntimeError("Unreachable") +```