Here is a quick algorithm puzzle that was asked during lecture.
Q: Suppose I have a data structure that is both a heap and a binary search tree. It stores N distinct elements. What is it?
A: Well, it must satisfy both the heap property (heaps) and the BST property. What are these properties?
heap property - all child elements are less than the parent element
BST property - every parent is greater than all of its subchildren on the left and less than all of its subchildren on the right.
So, how can we possibly support both of these properties in a simple, single data structure?
Easily, by creating a tree with only left children.
5
/ \
4
/ \
3
/ \
2
This is clearly both a heap and a tree.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment