//LeftistHeap是一个左式堆,本次主要描述的是对左式堆的合并操作的实现。其中包括创建左式堆的结构。
//左式堆的特点:对于堆中的每一个节点X,左儿子的零路径长至少与右儿子的零路径长相等。
public class LeftistHeap<AnyType extends Comparable<? super AnyType>> {
private LeftistHeapNode<AnyType> root;//root
public LeftistHeap(){
root = null;
}
public void merge(LeftistHeap<AnyType>rhs){
if(this == rhs){
return ;
}
root = merge(root, rhs.root);
rhs.root = null;
}
//递归的将具有大的根值的堆与具有小的根值的堆的右子堆合并
private LeftistHeapNode<AnyType> merge(LeftistHeapNode<AnyType>root1, LeftistHeapNode<AnyType> root2){
//注意测试用例,以及合法性的判断
if(root1 == null){
return root2;
}
if(root2 == null){
return root1;
}
if(root1.element.compareTo(root2.element) < 0){
return Merge(root1, root2);
}else{
return Merge(root2, root1);
}
}
private LeftistHeapNode<AnyType> Merge(LeftistHeapNode<AnyType> h1,LeftistHeapNode<AnyType> h2){
//测试用例(单节点情况)
if(h1.left == null){
h1.left = h2;//将左式堆h2的根节点赋给h1.left(用来保证npl)
}else {
h1.right = merge(h1.right, h2);//将左式堆h2的根节点赋给h1.right
if(h1.left.npl < h1.right.npl){
//swapChildren(h1);//该函数实现交换一个结点的左右子树。
}
h1.npl = h1.right.npl+1;//记录零路径长
}
return h1;
}
//定义左式堆结点的结构体
class LeftistHeapNode<AnyType>{
//Constructors
LeftistHeapNode(AnyType theElement) {
this(theElement, null, null);
}
LeftistHeapNode(AnyType theElement,LeftistHeapNode<AnyType> lt, LeftistHeapNode<AnyType> rt) {
// TODO Auto-generated constructor stub
element = theElement; left = lt; right = rt; npl = 0;
}
AnyType element;
LeftistHeapNode<AnyType> left;
LeftistHeapNode<AnyType> right;
int npl;//零路径长(null path length):从X到一个不具有两个儿子的节点的最短路径的长。
//具有0个或一个儿子的节点的npl为0.
}
}