优先队列中左式堆的合并算法

//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个或一个儿子的节点的npl0.

   }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值