A treap must keep its keys in binary-search-tree order while also satisfying a priority rule. After an insertion, a new leaf may be in the right place by key but the wrong place by priority. Swapping it with its parent could break key order; a rotation moves it up while preserving that order. section 3.3.1 section 3.3.4
A rotation reverses one parent–child relationship and reconnects the subtree between the two nodes:
- Right rotation: the left child X takes its parent Y’s place. Connect X’s former right subtree as Y’s left subtree, then make Y the right child of X. section 3.3.1
- Left rotation: the right child X takes Y’s place. Connect X’s former left subtree as Y’s right subtree, then make Y the left child of X. section 3.3.1
- In either direction, reconnect Y’s former parent to X—or update the tree’s root if Y was the root. An implementation must also keep parent links consistent. section 3.3.1
Moving a treap node
To insert an inventory entry, first place it as a BST leaf. If its priority violates the rule relative to its parent, rotate the new node upward; repeat if necessary. To delete an entry, rotate its highest-priority child upward until the entry becomes a leaf, then disconnect it. These are opposite uses of the same local operation. section 3.3.4 section 3.3.5
With pointer-linked nodes, one rotation changes a fixed number of links and takes constant time. A full insertion or deletion may need several rotations. Rotations can also make a tree less balanced, so a rotation alone is not a balancing guarantee. They are awkward for array-backed trees because moving the affected subtree can require linear-time work. section 3.3.1 section 3.3.2 section 3.4.1
Follow the right-rotation diagram to see where the child, parent, and intervening subtree reconnect. section 3.3.1

