template <class Type> void BinarySearchTree<Type> :: insert( const Type & x, BinaryNode<Type> * & t ) { if( t == NULL ) t = new BinaryNode<Type>( x, NULL, NULL ); else if( x < t->element ) insert( x, t->left ); else if( t->element < x ) insert( x, t->right ); else t->priority++; // Duplicate; do nothing for right now }
Now I need to figure out when the node is equal, how to re-order the tree so that the current node (who is equal to an already existing node) finds the existing node, increases that node’s priority, then shifts it up if the root is a lower priority. I think I have the idea down that the AVL logic would work, and when a shift would take place, it would be a single rotation right or a single rotation left. Here’s where I’m confused, don’t really know where to start with creating an algorithm to solve the problem. Since the AVL algorithm works with keeping track of the balance of a tree, then rotating nodes left or right accordingly, this tree doesn’t need to worry about being balanced, just that the nodes with the highest priority not have children with a higher priority.
Asked By : OghmaOsiris
Answered By : Raphael
- If you want to actually combine the ideas of priority queues and binary search trees, think about combining heap and BST in one structure.
- There is the concept of self-organising lists. The idea is to move recently accessed element to (or towards the) front in order to speed up future accesses to the same element, thusly “learning” the element distribution over time (with quality depending on the particular implementation). Maybe you can adapt this to trees?
Spoiler: Follow below links only if you have not been able to come up with something yourself.
1. This is called a treap.
2. Splay trees implement this idea.
Best Answer from StackOverflow
Question Source : http://cs.stackexchange.com/questions/559