Now, where are the Treaps, this is not what we started with?Here's the answer to this :
What if the situation is online instead of offline?
This means if we get values to be inserted in the BST on the go, instead of all at begining, we cannot do random permute in such a scenario.
Here we will use the heap property we introduced earlier, so lets say we have a max heap.
Our node has two values : key, priority
Key is used to maintain BST, and priority is used to maintain max-heap
We get only values, i.e., keys on the go, we randomnly generate a priority value for that node.
Then we insert the node using key in our Treap such as to satisfy the BST property, i.e., we perform the normal BST insertion.
Then we check if the heap property is satisfied or not, if the heap property is not satisfied, we perform rotations to make sure that the heap property is satisfied.
Such a thing has a high property that we maintain an almost balanced BST all the time, but remember its just a chance game, although the probability here is very high.
If you are curious how about high is the probabilty?
Note : There are other data structures such as Red Black Trees and AVL Trees for maintaining balanced BST. They do not use randomness and they guarantee that tree is a Balanced Binary Search Tree. They are more complex than Treaps.