|
| 1 | +""" |
| 2 | +Leftist heap: a mergeable min-heap stored as a binary tree. |
| 3 | +
|
| 4 | +Every node keeps its "rank" (the length of the shortest path down to a missing |
| 5 | +child) and the tree maintains the leftist property: the rank of the left child is |
| 6 | +never smaller than the rank of the right child. The right spine is therefore |
| 7 | +at most log2(n + 1) nodes long, and merging two heaps only walks right spines, |
| 8 | +so merge, insert and pop all run in O(log n). |
| 9 | +
|
| 10 | +https://en.wikipedia.org/wiki/Leftist_tree |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +from collections.abc import Iterable, Iterator |
| 16 | +from typing import Protocol, Self |
| 17 | + |
| 18 | + |
| 19 | +class Comparable(Protocol): |
| 20 | + def __lt__(self, other: Self, /) -> bool: ... |
| 21 | + |
| 22 | + |
| 23 | +class LeftistNode[T: Comparable]: |
| 24 | + def __init__(self, value: T) -> None: |
| 25 | + self.value = value |
| 26 | + self.rank = 1 |
| 27 | + self.left: LeftistNode[T] | None = None |
| 28 | + self.right: LeftistNode[T] | None = None |
| 29 | + |
| 30 | + |
| 31 | +def _rank[T: Comparable](node: LeftistNode[T] | None) -> int: |
| 32 | + return 0 if node is None else node.rank |
| 33 | + |
| 34 | + |
| 35 | +def _merge_nodes[T: Comparable]( |
| 36 | + first: LeftistNode[T] | None, second: LeftistNode[T] | None |
| 37 | +) -> LeftistNode[T] | None: |
| 38 | + """ |
| 39 | + Merge two leftist trees and return the root of the result. |
| 40 | +
|
| 41 | + >>> _merge_nodes(None, None) is None |
| 42 | + True |
| 43 | + >>> node = LeftistNode(3) |
| 44 | + >>> _merge_nodes(node, None) is node |
| 45 | + True |
| 46 | + >>> _merge_nodes(None, node) is node |
| 47 | + True |
| 48 | + >>> merged = _merge_nodes(LeftistNode(5), LeftistNode(2)) |
| 49 | + >>> merged.value, merged.left.value |
| 50 | + (2, 5) |
| 51 | + """ |
| 52 | + if first is None: |
| 53 | + return second |
| 54 | + if second is None: |
| 55 | + return first |
| 56 | + if second.value < first.value: |
| 57 | + first, second = second, first |
| 58 | + first.right = _merge_nodes(first.right, second) |
| 59 | + if _rank(first.left) < _rank(first.right): |
| 60 | + first.left, first.right = first.right, first.left |
| 61 | + first.rank = _rank(first.right) + 1 |
| 62 | + return first |
| 63 | + |
| 64 | + |
| 65 | +class LeftistHeap[T: Comparable]: |
| 66 | + """ |
| 67 | + Min-heap supporting O(log n) insert, pop and merge. |
| 68 | +
|
| 69 | + >>> heap = LeftistHeap([5, 3, 8, 1, 9, 2]) |
| 70 | + >>> len(heap) |
| 71 | + 6 |
| 72 | + >>> heap.peek() |
| 73 | + 1 |
| 74 | + >>> [heap.pop() for _ in range(len(heap))] |
| 75 | + [1, 2, 3, 5, 8, 9] |
| 76 | + >>> bool(heap) |
| 77 | + False |
| 78 | + >>> heap.pop() |
| 79 | + Traceback (most recent call last): |
| 80 | + ... |
| 81 | + IndexError: pop from an empty heap |
| 82 | + >>> heap.peek() |
| 83 | + Traceback (most recent call last): |
| 84 | + ... |
| 85 | + IndexError: peek from an empty heap |
| 86 | +
|
| 87 | + >>> first = LeftistHeap([4, 10, 6]) |
| 88 | + >>> second = LeftistHeap([7, 1, 5]) |
| 89 | + >>> first.merge(second) |
| 90 | + >>> list(first) |
| 91 | + [1, 4, 5, 6, 7, 10] |
| 92 | + >>> len(second) |
| 93 | + 0 |
| 94 | + >>> list(LeftistHeap(["pear", "apple", "fig"])) |
| 95 | + ['apple', 'fig', 'pear'] |
| 96 | + >>> list(LeftistHeap([2, 2, 1, 1])) |
| 97 | + [1, 1, 2, 2] |
| 98 | + """ |
| 99 | + |
| 100 | + def __init__(self, items: Iterable[T] = ()) -> None: |
| 101 | + self._root: LeftistNode[T] | None = None |
| 102 | + self._size = 0 |
| 103 | + for item in items: |
| 104 | + self.insert(item) |
| 105 | + |
| 106 | + def __len__(self) -> int: |
| 107 | + """ |
| 108 | + >>> len(LeftistHeap([1, 2])) |
| 109 | + 2 |
| 110 | + """ |
| 111 | + return self._size |
| 112 | + |
| 113 | + def __iter__(self) -> Iterator[T]: |
| 114 | + """Yield the values in ascending order without modifying the heap.""" |
| 115 | + copy = LeftistHeap[T]() |
| 116 | + copy._root = self._copy_tree(self._root) |
| 117 | + copy._size = self._size |
| 118 | + while copy: |
| 119 | + yield copy.pop() |
| 120 | + |
| 121 | + @staticmethod |
| 122 | + def _copy_tree(node: LeftistNode[T] | None) -> LeftistNode[T] | None: |
| 123 | + """ |
| 124 | + >>> LeftistHeap._copy_tree(None) is None |
| 125 | + True |
| 126 | + """ |
| 127 | + if node is None: |
| 128 | + return None |
| 129 | + clone = LeftistNode(node.value) |
| 130 | + clone.rank = node.rank |
| 131 | + clone.left = LeftistHeap._copy_tree(node.left) |
| 132 | + clone.right = LeftistHeap._copy_tree(node.right) |
| 133 | + return clone |
| 134 | + |
| 135 | + def insert(self, value: T) -> None: |
| 136 | + """ |
| 137 | + >>> heap = LeftistHeap[int]() |
| 138 | + >>> heap.insert(4) |
| 139 | + >>> heap.insert(2) |
| 140 | + >>> heap.peek() |
| 141 | + 2 |
| 142 | + """ |
| 143 | + self._root = _merge_nodes(self._root, LeftistNode(value)) |
| 144 | + self._size += 1 |
| 145 | + |
| 146 | + def peek(self) -> T: |
| 147 | + """ |
| 148 | + >>> LeftistHeap([7, 3]).peek() |
| 149 | + 3 |
| 150 | + """ |
| 151 | + if self._root is None: |
| 152 | + raise IndexError("peek from an empty heap") |
| 153 | + return self._root.value |
| 154 | + |
| 155 | + def pop(self) -> T: |
| 156 | + """ |
| 157 | + >>> heap = LeftistHeap([7, 3]) |
| 158 | + >>> heap.pop(), heap.pop() |
| 159 | + (3, 7) |
| 160 | + """ |
| 161 | + if self._root is None: |
| 162 | + raise IndexError("pop from an empty heap") |
| 163 | + smallest = self._root.value |
| 164 | + self._root = _merge_nodes(self._root.left, self._root.right) |
| 165 | + self._size -= 1 |
| 166 | + return smallest |
| 167 | + |
| 168 | + def merge(self, other: LeftistHeap[T]) -> None: |
| 169 | + """ |
| 170 | + Move every element of ``other`` into this heap, leaving ``other`` empty. |
| 171 | +
|
| 172 | + >>> heap = LeftistHeap([2]) |
| 173 | + >>> heap.merge(heap) |
| 174 | + >>> len(heap) |
| 175 | + 1 |
| 176 | + """ |
| 177 | + if other is self: |
| 178 | + return |
| 179 | + self._root = _merge_nodes(self._root, other._root) |
| 180 | + self._size += other._size |
| 181 | + other._root = None |
| 182 | + other._size = 0 |
| 183 | + |
| 184 | + |
| 185 | +if __name__ == "__main__": |
| 186 | + import doctest |
| 187 | + |
| 188 | + doctest.testmod() |
0 commit comments