Leftist Heaps
Npl(X)
Npl(Leaf)=0
Npl(x)=min{Npl(child)}+1
Leftist Heap
1.order property:要求满足父亲小于任何一个子节点。
2.Structure Property:要求是二叉树即可
3.leftist heap property:任意一个节点,左子节点的Npl大于等于右子节点
A leftist tree with r nodes on the right path must have at least 2^r – 1 nodes.
Merge
思路是:
1.两棵树合并,将小的根作为根连上去,
2.另一棵树和根的右孩子合并。
3.直到右节点为NULL,直接插入
4.完成后进行回溯:从下往上检查上去,如果出现了Npl右边大的情况,左右孩子进行交换
struct TreeNode
{
ElementType Element;
PriorityQueue Left;
PriorityQueue Right;
int Npl;
} ;
PriorityQueue Merge ( PriorityQueue H1, PriorityQueue H2 )
{
if ( H1 == NULL ) return H2;
if ( H2 == NULL ) return H1;
if ( H1->Element < H2->Element ) return Merge1( H1, H2 );
else return Merge1( H2, H1 );
}
static PriorityQueue
Merge1( PriorityQueue H1, PriorityQueue H2 )
{
if ( H1->Left == NULL ) /* single node */
H1->Left = H2; /* H1->Right is already NULL
and H1->Npl is already 0 */
else {
H1->Right = Merge( H1->Right, H2 ); /* Step 1 & 2 */
if ( H1->Left->Npl < H1->Right->Npl )
SwapChildren( H1 ); /* Step 3 */
H1->Npl = H1->Right->Npl + 1;
} /* end else */
return H1;
}
1.3和6合并,3为根
2.6和8合并,6为根
3.8和7合并,7为根
4.8和18合并,8为根
5.交换7的孩子
6.交换3的孩子
Merge注意的问题
1.关于交换的问题:那些被插入过的根需要交换,就是说,从一开始右侧为NULL的节点往上到根,这些全部需要交换(如果不满足左边Npl更大的条件)
2.左侧的子树照抄,然后右侧的子树确定根,写上去,再照抄左侧的
3.交换的时候,本来的左右子树不要搞错了。左子树不要交换了一下画到了右边。一个方法是:先画右边一直到叶子,然后补上左节点到叶子,就是按照DFS的顺序。
DeleteMin
1.删除根
2.Merge(root->left,root->right)
复杂度
插入,删除,merge均为log(N)
Skew Heaps
Skew heaps have the advantage that
1.no extra space is required to maintain path lengths
2.no tests are required to determine when to swap children.
Merge
Always swap the left and right children except that the largest of all the nodes on the right paths does not have its children swapped.
1.谁小谁是根
2.和根的有孩子Merge
3.直到有孩子为NULL时结束
4.按照Merge的路径回溯,交换孩子
插入15
1.3为根,和10merge
2.10为根,和14merge
3.14为根,右孩子为NULL,直接插入
4.交换14的孩子
5.交换10的孩子
6.交换3的孩子
复杂度
heavy:右边的子树节点 >= 左边子树的节点+1。
light就是小于
势能函数选取为phi(Di)是Di为根的树heavy节点个数
发现规律是:只有当初在节点右子树上的点,其heavy或者light的属性可能发生变化。
两个堆右侧节点数为heavy和light节点数之和:
H1=h1+l1
H2=h2+l2
最多的操作次数是:
T=h1+l1+h2+l2
phi0=h1+h2+h
heavy节点在合并后是light,light可能变为heavy
势能最大的情况是light全部变成heavy
phiN<l1+l2+h
phiN-phi0<=l1+l2-h1-h2<2(l1+l2)
平均复杂度为O(logN)