1. 程式人生 > >左式堆實現

左式堆實現

per delet tis div ont nod 大於等於 eem val

左式堆是為了方便合並操作實現的。

左式堆性質:

任意節點X的零路徑長是X到任意沒有兩個兒子的節點的最短路徑。任意一個節點的零路徑長比他兒子的零路徑長的最大值大1,null的零路徑長是-1;對於x來說,他的左兒子的零路徑長要大於等於右兒子。

通過遞歸實現代碼如下

public class LeftistHeap<T extends Comparable<? super T>>{
    private Node<T> root;
    
    public LeftistHeap(){
        this.root=null;
    }
    
public void merge(LeftistHeap<T> rhs){ if(this.root==rhs.root){ return; } merge(this.root, rhs.root); rhs.root=null; } private Node<T> merge(Node<T> t1,Node<T> t2){ if(t1==null){ return t2; }
if(t2==null){ return t1; } if(t1.val.compareTo(t2.val)<0){ return merge1(t1, t2); } else{ return merge1(t2, t1); } } private Node<T> merge1(Node<T> t1,Node<T> t2){ if(t1.left==null
){ t1.left=t2; }else{ t1.right=merge(t1.right, t2); if(t1.left.npl<t1.right.npl){ swapChildren(t1); } t1.npl=t1.right.npl+1; } return t1; } public void insert(T val){ merge(new Node(val),root); } public T findMin(){ return root.val; } public T deleteMin(){ T val=root.val; root=merge(root.left,root.right); return val; } public boolean isEmpty(){ return root==null; } public void makeEmpty(){ root=null; } private void swapChildren(Node<T> t){ Node<T> left=t.left; Node<T> right=t.right; t.left=right; t.right=left; } }

左式堆實現