CS 6310 Advanced Data Structure Wei-Shian Wang Heaps CS 6310 Advanced Data Structure Wei-Shian Wang
Also called priority queues Support operations: insert, find_min, delete_min Min-heap and max-heap
5.1 Balanced Search Trees as Heaps
insert : O(log n) find_min : O(log n) O(1) delete_min : O(log n)
Make find_min in O(1) Store the current minimum in a variable Look up the new current minimum in O(log n) time when we perform the next delete_min
delete_min – O(1) Delete the object current_min->object Move current_min to the next list position If current_min->key is now larger than the key in the root of the balanced tree, add the left subtree of the balanced search tree to the invalid nodes structure; take the right subtree as new search tree; and return the node of the old root to the free list Return several nodes from the invalid nodes structure to the free list
insert – O(log n) find_min – O(1) Split the search tree at current_min->key, and add the lower tree to the invalid nodes structure Insert the new key in search tree If the key is below current_min->key, set current_min to the new key and object find_min – O(1) Return current_min->key and current_min->object
Theorem. The heap structure can be realized using a balanced search tree with lazy deletion in time O(log n) for insert and O(1) for find_min and delete_min operations if the heap contains n element.
5.4 Leftist Heaps
Leftist Heap Properties Each node contains an additional field, the rank, which is defined by n->rank = 1 if n->left = NULL or n->right = NULL n->rank = 1 + Min(n->left->rank, n->right->rank) if n->left ≠ NULL and n->right ≠ NULL Heap is empty if root->rank = 0
Most nodes are on the left All the merging work is done on the right Each node in a leftist heap has the shortest path on the left side is at least as long as that on the right side: n->left->rank ≧ n->right->rank If they are not both defined, then if one of them exists, it is the left one: n->left = NULL only if n->right = NULL Most nodes are on the left All the merging work is done on the right
insert O(log n)
delete_min and merge O(log n)
Theorem. The leftist heap structure supports the operation find_min in O(1) time and insert, merge, and delete_min in O(log n) time
Leftist Heap Visualization https://www.cs.usfca.edu/~galles/visualization/LeftistHeap.html
Thank you !