如何在堆数据结构中删除?

编程入门 行业动态 更新时间:2024-10-26 02:29:15
本文介绍了如何在堆数据结构中删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我了解如何从最大堆中删除根节点,但是从中间删除节点的过程是否反复删除和替换根,直到所需的节点被删除?

  • O(log n)是否为此过程的最佳复杂性?

  • 这是否影响大O复杂度,因为其他节点必须删除才能删除特定节点?

  • 解决方案>

    实际上,您可以从堆中间移除一个项目,而不会有麻烦。

    想法是将堆中的最后一个项目从当前位置(即保持您删除的项目的位置),如果新项目大于旧项目的父项,则将其筛选。如果不超过父级,则将其筛选。

    这是最大堆的过程。对于一个最小的堆,当然,你会扭转越来越多的情况。

    查找堆中的一个项目是一个O( n)操作,但是如果你已经知道它在堆中的位置,删除它是O(log n)。

    我发布了一个基于堆的优先级队列为DevSource几年前。请参阅 C#中的优先级队列实现。它有一个 RemoveAt 方法,完全符合我所描述的。

    完整的源代码是 www.mischel/pubs/priqueue.zip

    I understand how to delete the root node from a max heap but is the procedure for deleting a node from the middle to remove and replace the root repeatedly until the desired node is deleted?

  • Is O(log n) the optimal complexity for this procedure?

  • Does this affect the big O complexity since other nodes must be deleted in order to delete a specific node?

  • 解决方案

    Actually, you can remove an item from the middle of a heap without trouble.

    The idea is to take the last item in the heap and, starting from the current position (i.e. the position that held the item you deleted), sift it up if the new item is greater than the parent of the old item. If it's not greater than the parent, then sift it down.

    That's the procedure for a max heap. For a min heap, of course, you'd reverse the greater and less cases.

    Finding an item in a heap is an O(n) operation, but if you already know where it is in the heap, removing it is O(log n).

    I published a heap-based priority queue for DevSource a few years back. See A Priority Queue Implementation in C#. It has a RemoveAt method that does exactly what I described.

    Full source is at www.mischel/pubs/priqueue.zip

    更多推荐

    如何在堆数据结构中删除?

    本文发布于:2023-10-14 22:42:18,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1492426.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:数据结构   如何在

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!