Binomial heap
A forest of binomial trees of distinct degrees, like the binary digits of n; merging two heaps works like adding two binary numbers and takes O(log n).
The binomial tree of degree k, B_k, is two copies of B_{k−1} with one root made a child of the other. So it has
2^k nodes and its root has k children.
- Time:
O(log n) per union, insert or extract-min - Space:
O(n) - Horowitz–Sahni, chapter 9
- CLRS, chapter 19
Seven inserts: 7 = 111 in binary, so three trees of 1, 2 and 4 nodes remain. Then an extract-min.
class Node:def __init__(self, key):self.key = keyself.degree = 0self.children = [] # in increasing degreedef binomial_heap(ops):heap = [] # the root list, in increasing degreeremoved = []for x in ops:if x > 0:union(heap, [Node(x)])elif not heap:continueelse:m = heap[0]for r in heap:if r.key < m.key:m = rheap.remove(m)removed.append(m.key)union(heap, m.children)return removeddef union(heap, other):# Merge the two root lists by degree, then link trees of equal degree, like adding binary numbers.heap.extend(other)heap.sort(key=lambda t: t.degree)i = 0while i < len(heap) - 1:x = heap[i]nx = heap[i + 1]if x.degree != nx.degree:i = i + 1elif i + 2 < len(heap) and heap[i + 2].degree == x.degree:i = i + 1elif x.key <= nx.key:link(nx, x)heap.pop(i + 1)else:link(x, nx)heap.pop(i)def link(y, z):# Two trees of degree k become one of degree k + 1: y goes under z.z.children.append(y)z.degree = z.degree + 1
Start
∅
Local variables
Orange = changed in this step
ops list
Call stack
- binomial_heap()line 8
Explanation
Binomial trees
The binomial tree of degree k, B_k, is two copies of B_{k−1} with one root made a child of the other. So it has
2^k nodes and its root has k children.
Binomial heaps
A collection of heap-ordered binomial trees, at most one of each degree. The trees present are exactly the 1
digits of n in binary, so there are at most ⌊log n⌋ + 1 of them.
Union is binary addition
Put the two root lists side by side in order of degree. Wherever two trees share a degree, link them: the larger root goes under the smaller, giving one tree of the next degree, like a carry in addition. If three trees of one degree sit together, step over the first and link the next two.
- Insert: union with a one-node heap.
- Extract-min: the minimum is one of the roots; take it out and union its children (themselves a binomial heap) back in.
The input
A positive number is inserted and 0 means extract-min.