A skew heap (or self – adjusting heap) is a heap data structure implemented as a binary tree. Skew heaps are advantageous because of their ability to merge more quickly than binary heaps. In contrast with binary heaps, there are no structural constraints, so there is no guarantee that the height of the tree is logarithmic. Only two conditions must be satisfied :
- The general heap order must be there (root is minimum and same is recursively true for subtrees), but balanced property (all levels must be full except the last) is not required.
- Main operation in Skew Heaps is Merge. We can implement other operations like insert, extractMin(), etc using Merge only.
1. Consider the skew heap 1 to be
2. The second heap to be considered
4. And we obtain the final merged tree as
Recursive Merge Process :
- Let h1 and h2 be the two min skew heaps to be merged. Let h1’s root be smaller than h2’s root (If not smaller, we can swap to get the same).
- We swap h1->left and h1->right.
- h1->left = merge(h2, h1->left)
Let h1 be 10 / \ 20 30 / / 40 50 Let h2 be 15 / \ 25 35 / \ 45 55 After swapping h1->left and h1->right, we get 10 / \ 30 20 / / 50 40 Now we recursively Merge 30 / AND 50 15 / \ 25 35 / \ 45 55 After recursive merge, we get (Please do it using pen and paper). 15 / \ 30 25 / \ / \ 35 50 45 55 We make this merged tree as left of original h1 and we get following result. 10 / \ 15 20 / \ / 30 25 40 / \ / \ 35 40 45 55
The heap obtained after merging is: 12 8 5 10 3 14 7
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.