删除优先级队列的第k个元素

假定是最小堆。

伪代码:

    1, Delete a node from the array 
       (this creates a "hole" and the tree is no longer "complete")

    2. Replace the deletion node
       with the "fartest right node" on the lowest level
       of the Binary Tree
       (This step makes the tree into a "complete binary tree")

    3. Heapify (fix the heap):

         if ( value in replacement node < its parent node )
            Filter the replacement node UP the binary tree
         else
	    Filter the replacement node DOWN the binary tree

JAVA:

   public double remove( int k )
   {
      int parent;
      double r;             // Variable to hold deleted value

      r = a[k];             // Save return value

      a[k] = a[NNodes];     // Replace deleted node with the right most leaf
                            // This fixes the "complete bin. tree" property

      NNodes--;             // One less node in heap....

      parent = k/2;

      /* =======================================================
	 Filter a[k] up or down depending on the result of:
		a[k] <==> a[k's parent]
         ======================================================= */
      if ( k == 1 /* k is root */ || a[parent] < a[k] ) 
         HeapFilterDown(k);  // Move the node a[k] DOWN the tree
      else
         HeapFilterUp(k);    // Move the node a[k] UP the tree

      return r;         // Return deleted value...
   }

HeapFilterDown, HeapFilterUp就是下沉和上浮操作。

参考:

http://www.mathcs.emory.edu/~cheung/Courses/171/Syllabus/9-BinTree/heap-delete.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值