简体   繁体   English

在堆中找到最大值(方案)

[英]Finding the max value in a heap (Scheme)

I'm trying to return a function that returns the maximum value in a heap (where the heap goes from min on top to max on the bottom). 我试图返回一个函数,该函数返回堆中的最大值(其中堆从顶部的min到底部的max)。 I understand how I could do something similar to this in BST. 我了解如何在BST中执行类似的操作。 But I don't know how I would do this in a heap because I don't completely understand the organization for heaps. 但是我不知道如何在堆中执行此操作,因为我不完全了解堆的组织。 In a BST I would just keep going to the left until I get to the end. 在BST中,我将一直向左移动直到结束。 But if I keep going towards the bottom of a heap, there's a chance that the maximum value is on the other subtree. 但是,如果我继续接近堆的底部,则最大值有可能在另一个子树上。 (Not sure if that made complete sense). (不确定是否完全有意义)。 Any help in how to approach this would be appreciated. 任何帮助如何解决这一问题将不胜感激。 Thanks in advance. 提前致谢。

*edit *编辑

So I thought of a different way to approach this but it's not correct. 因此,我想到了另一种方法来解决此问题,但这是不正确的。 Basically after coming to the conclusion that heaps are just a bunch of nested lists, I made a code that makes the heap into one list and uses another helper function that gets the max value. 基本上得出了堆只是一堆嵌套列表的结论之后,我编写了一个代码,使堆成为一个列表,并使用另一个获得最大值的帮助器函数。 But how would I approach this by actually going through and looking at each individual node? 但是,我将如何通过实际检查每个节点来解决这个问题?

Right, in a min-heap each node is only guaranteed to be greater than it's parent. 正确,在最小堆中,仅保证每个节点都大于其父节点。 A full walk will give a solution, but you can be a little smarter by realizing the maximum will be in a singleton tree at the bottom of the structure. 完整的步行可以找到解决方案,但是您可以通过在结构底部的单例树中实现最大值来变得更聪明。 You can also use let to force evaluation of the leftmost tree first. 您还可以使用let强制首先评估最左边的树。 Assuming a binary structure for the heap. 假设堆为二进制结构。

(define (max-heap min-heap)
  ((empty-heap? min-heap)
   (error "empty heap has no maximum")
  ((singleton? min-heap)
   (node min-heap))
  ((empty-heap? (left-heap min-heap))
   (max-heap (right-heap min-heap)))
  ((empty-heap? (right-heap min-heap))
   (max-heap (left-heap min-heap)))
  (else 
   (let ((left-max (max-heap (left-heap min-heap))))
     (let ((right-max (max-heap (right-heap))))
       (if (> left-max right-max) left-max right-max))))))

You still have to walk the whole tree, but you only need to do it once. 您仍然必须步行整棵树,但只需要执行一次。 And your stack is only ever as big as the depth of the heap. 而且您的堆栈仅与堆的深度一样大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM