Binomial Heap

advertisement
CS 261
Binary Heaps
A Different Type of Heap
• Start with the same heap order
property, but build it out of binomial
trees
• Use a collection of heaps
• Merge heaps of the same size
Binomial Tree
• A recursive data structure
• A node has binomial trees of lower
order as children, from order k down to
order 0
A picture!
Overcoming Limitations of the
Tree
• Can only keep things which are a sum
of a power of 2
• But if we keep a list of trees we can get
any number of nodes
• Like binary numbers
What it looks like
Our Powers Combined!
• Merging is a key operation
• Many other operations will call merge as
a subroutine
• Takes two heaps and merges them
Merging Trees
• If we have two trees of the same size how do
we merge them?
• Just make the one with the bigger key the
leftmost child of the root of the other
Merging heaps
• Look at each tree in the list from
smallest to biggest
• If only one heap has a tree of order n,
add it to the merged heap
• Otherwise merge the two trees into a
tree of order n+1 and merge that into
the new heap
Moar Pictures! (Merging)
Adding To a Heap
• How do we add to a binomial heap?
• Can we just use merge somehow?
Finding the Minimum
• Is it still O(1)?
• If it is not, can we be tricky and make it
so?
Removing the minimum
• The minimum will always be a root
• Remove that root, then merge the
resulting heap with the old heap
It’s All log(n)
• Or maybe find minimum is O(1) if we
are smart about it
Download