PhilosophyBST maintains a global property, heap a local one
The top node ofThis local property, unlike for BSTs, then also implies by itself a heap is the smallglobal property: an element, which only requires local knowledge to maintain (knowing your parent) is smaller than all children.
ThereBut there is no guarantee that "everything to the left is smaller than everything to the right" as for BST.
It is also interesting to consider what would happen if we only enforced a local property for BST:
left child is smaller, right child is larger
The problem with this is that because there are two possible directions to consider, smaller or greater, the second level descendant may break the global property, for example consider:
# Fake BST with local property only 5 / \ 3 7 / \ 1 9 Here, we have the property that "left child is smaller, right child is bigger" for all nodes.
But as we go smaller to 3, the next level can get arbitrarily large to the right, here going up to 9, which is above 5, and so we don't have a global property.
The only global property that would be enforced by that rule alone is if we only go down all the way left we decrease, or all the way right we increase.
In the case of the heap, there is only one possible direction: smaller or bigger at each step, so the global property is also implied.
LRU cache: efficient approach if all insertions are guaranteed to be thenthe max or min
If every time you insert something it is always the maximum or minimum, there's an even more efficient approach to things: you can just keep a hash map to nodes of a linked list: https://stackoverflow.com/questions/2504178/lru-cache-design
)
