Another variation of a binary search tree is a treap, which is a tree in which the nodes maintain two values:
The data fields will be ordered using binary search tree properties and the priority fields will be ordered using heap order properties.
If the heap order is to maintain a max heap, then:
If the heap order is to maintain a min heap, then:
Searching a treap is implemented in the same manner as the searching of a binary search tree.
Insertion of a node into a treap must ensure that both binary search tree and heap order properties are maintained. To do this, insert the node as a leaf node following binary search tree properties. If the heap order property is violated, then it will be restored by applying a rotation.
If the new node was inserted as a left child, then a right rotation will be performed with the inserted node and its parent.
If the new node was inserted as a right child, then a left rotation will be performed with the inserted node and its parent.
Deletion of a node from a treap must ensure that both binary search tree and heap order properties are maintained throughout the treap. This is done by only deleting leaf nodes from the treap.
If the node to be deleted is already a leaf node, then simply delete it from the treap, making sure to set its parent's appropriate child pointer to null.
If the node to be deleted is not a leaf node, it will be rotated down the treap until it becomes a leaf node. If the left child of the node to be deleted has a higher priority than the right child of the node to be deleted, then a right rotation will be performed with the node to be deleted and its left child.
If the right child of the node to be deleted has a higher priority than the left child of the node to be deleted, then a left rotation will be performed with the node to be deleted and it's right child.
This process will be repeated until the node to be deleted becomes a leaf node.
Delete the node with key 4 from the following treap: