对于堆中每一个X节点,左儿子的零路径长至少与右儿子的零路径长相等。
零路径长:从X到一个不具有两个儿子的节点的最短路径长。
函数复杂度比较
1)获取最小值: O(1)
2)删除Min: O(Log n)
3)插入: O(Log n)
4)合并: O(Log n)
节点:
class LeftHeapNode
{
int element, sValue;
LeftHeapNode left, right;
public LeftHeapNode(int ele)
{
this(ele, null, null);
}
public LeftHeapNode(int ele, LeftHeapNode left, LeftHeapNode right)
{
this.element = ele;
this.left = left;
this.right = right;
this.sValue = 0;
}
}
操作API:
/** Class LeftistHeap **/
class LeftistHeap
{
private LeftHeapNode root;
/** Constructor **/
public LeftistHeap()
{
root = null;
}
/** Check if heap is empty **/
public boolean isEmpty()
{
return root == null;
}
/** Make heap empty **/
public void clear( )
{
root = null;
}
/** Function to insert data **/
public void insert(int x )
{
root = merge(new LeftHeapNode( x ), root);
}
/** Function merge **/
public void merge(LeftistHeap rhs)
{
if (this == rhs)
return;
root = merge(root, rhs.root);
rhs.root = null;
}
/** Function merge **/
private LeftHeapNode merge(LeftHeapNode x, LeftHeapNode y)
{
if (x == null)
return y;
if (y == null)
return x;
if (x.element > y.element)
{
LeftHeapNode temp = x;
x = y;
y = temp;
}
x.right = merge(x.right, y);
if(x.left == null)
{
x.left = x.right;
x.right = null;
}
else
{
if(x.left.sValue < x.right.sValue)
{
LeftHeapNode temp = x.left;
x.left = x.right;
x.right = temp;
}
x.sValue = x.right.sValue + 1;
}
return x;
}
/** Function to delete minimum element **/
public int deleteMin( )
{
if (isEmpty() )
return -1;
int minItem = root.element;
root = merge(root.left, root.right);
return minItem;
}
/** Inorder traversal **/
public void inorder()
{
inorder(root);
System.out.println();
}
private void inorder(LeftHeapNode r)
{
if (r != null)
{
inorder(r.left);
System.out.print(r.element +" ");
inorder(r.right);
}
}
}
非递归的merge实现:
private LeftHeapNode mergeV2(LeftHeapNode h1, LeftHeapNode h2) {
if (h1 == null) {
return h2;
}
if (h2 == null) {
return h1;
}
if (h1.element < h2.element ) {
return mergeV2_1(h1, h2);
} else {
return mergeV2_1(h2, h1);
}
}
private LeftHeapNode mergeV2_1(LeftHeapNode h1, LeftHeapNode h2) {
if (h1.left == null) {
h1.left = h2;
} else {
h1.right = mergeV2(h1.right,h2);
if (h1.left.sValue < h1.right.sValue) {
swapChildren(h1);
}
h1.sValue = h1.right.sValue + 1;
}
return h1;
}
private void swapChildren(LeftHeapNode t) {
LeftHeapNode temp = t.right;
t.right = t.left;
t.left = temp;
}
引用:https://www.sanfoundry.com/java-program-implement-leftist-heap/
https://www.geeksforgeeks.org/leftist-tree-leftist-heap/
https://www.youtube.com/watch?v=y2mipTl823k
https://www.youtube.com/watch?v=RFCd3JUGhys
《数据结构与算法(Java语言描述)第二版》