简体   繁体   中英

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). I understand how I could do something similar to this in 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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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