# Treaps

**Treaps** are a non-deterministic data structure in the form of a Cartesian Tree used to maintain a Balanced Binary Search Tree. As opposed to most other Balanced Binary Search Trees like scapegoat tree, red-black tree, avl tree, etc, the treap data structure does not *guarantee* balance, per se but ensures so with a very high probability.

#### Contents

## Cartesian Trees and Structure of the Treap

Treaps are **cartesian trees**, which means that they are trees with an ordered pair, and the nodes follow the binary search tree property with respect to one of them and the heap property with respect to the other.

This means that the treap is composed of \(n\) nodes, each of which is a pair \((H_i, B_i)\), called the priority and the key respectively, where for every node \(i\):

- \(H_{left(i)} \leq H_i \geq H_{right(i)}\) and
- \(B_{left(i)} \leq B_i \leq B_{right(i)}\)

Given a set of \((H_i, B_i)\) pairs, there exists an unique cartesian tree made by them.

If the list of pairs is empty, then we construct the empty tree and we're done.

Otherwise, we pick the root node as the pair with the highest priority and recursively build the left subtree with all the pairs whose keys are less than (or equal to) that of the root and the right subtree with all the pairs whose keys are greater than that of the root.

Treaps are cartesian trees where the priorities are chosen

at randomfrom a large range of integers.

We do not prove this here, but it is intuitively obvious that the expected height of the treap is in \(O(\lg n)\)

Thus, each node of the treap consists of a value, a priority, and pointers towards its two children (which may be null)

## Insertion

We'll build the tree by inserting an element one by one. Let us look at our first strategy to do this.

Insert blindly only using the binary search tree property. Using a random value as the priority,

rotatethe node up to the appropriate location.

We do not define

rotationsformally here, but illustrate with a graphicNotice that the BST invariant remains intact under this operation.