Binary Search Trees in Lean Check a result Declarations Bibliography Lean source

Chapter 32Treaps

Chapter 12 states that every arborally satisfied point set can be executed by a binary search tree that touches exactly one node per point. The proof, due to Demaine, Harmon, Iacono, Kane and Pătraşcu (2009), is a data structure: a treap whose priorities are the times at which keys will next be touched. The converse, that the touched nodes of any rooted-region execution form an arborally satisfied set, rests on the mirror-image invariant, a heap of the times at which keys were last touched. This chapter presents the definitions these two arguments are built from, and how the proofs use them.

Together the two arguments prove the exact form of the equivalence, with no constant factors at all: a point set and a BST execution in the rooted-region model of Chapter 8 cost the same.

The last two sections leave the geometric setting. They state the classical facts about treaps for arbitrary distinct priorities, and define the random treaps that Lazy Finger Theorem 1 uses in Chapter 15, and that give the expected depths of random search trees in Chapter 22.

Main result · Demaine et al. 2009
Arborally satisfied sets are exactly rooted-region executions

For every nn, every request sequence X=x0,x1,…X = x_0, x_1, \dots and every number cc, the following are equivalent:

  • there is an arborally satisfied set of exactly cc points, with keys less than nn and times less than ∣X∣|X|, that contains the point (xi,i)(x_i, i) of every request;
  • some BST on nn keys can serve XX in the rooted-region model, touching exactly cc nodes in total.

The initial tree is not fixed: the construction chooses it, and it needs the whole sequence in advance. In Lean, the point sets are Geometric.Offline solutions and the executions are RegionExecutions.

The Lean statement
theoremGeometric.Equivalence.Results.ass_iff_region_executionpropext · Classical.choice · Quot.soundModels/Equivalence/Abstract.lean:15
/-- Exact point-count equivalence with rooted-subtree BST executions.The initial tree is free; the conversion is offline. -/theorem ass_iff_region_execution (n : Nat) (xs : List Nat) (cost : Nat) :    (∃ E : Offline n xs, E.points.card = cost) ↔      ∃ s t, s.size = n ∧ RegionExecution s xs t cost := … offline_iff_regions n xs cost
17 definitions in 4 chapters · reading list

Apart from Geometric.Heap, which the general treap facts at the end of the chapter use, none of the definitions of the next five sections appears in a theorem statement of the reading interface. They live in Structures/Treap/Abstract.lean, Models/Region/Abstract.lean and Models/Region/View/Abstract.lean, and they are shown so that the proofs of Results.ass_iff_region_execution and Results.ass_to_pointers can be followed in the source. The regions and region executions they manipulate were defined in Chapter 8, and points, rows and arboral satisfaction in Chapter 9.

32.1 Treaps on ranks

A treap, introduced by Aragon and Seidel at FOCS 1989 (Seidel and Aragon 1996) and the same object as a Cartesian tree (Vuillemin 1980), is a binary search tree whose nodes also carry priorities, arranged in heap order: every node has priority at most that of each of its descendants. When priorities are distinct, the treap on a given key set is unique: its root is the key of minimum priority, and its two subtrees are the treaps of the keys on either side. On shapes, where keys are inorder ranks, heap order is a property of a shape and a priority function on ranks:

defGeometric.Heapno axiomsStructures/Treap/Abstract.lean:15
/-- A treap on consecutive inorder ranks. Each subtree root has minimumpriority in its interval. Equal priorities impose no extra tie-breaking rule. -/def Heap {α : Type} [LE α] (priority : Nat → α) : Tree → Nat → Prop  | .nil, _ => True  | .node l r, lo =>      (∀ x < l.size + 1 + r.size, priority (lo + l.size) ≤ priority (lo + x)) ∧      Heap priority l lo ∧ Heap priority r (lo + l.size + 1)

Heap priority t lo reads the subtree t as holding the ranks lo, lo+1, …, lo + t.size - 1, as in Chapter 1. Its root lo + l.size must have priority at most that of every rank lo + x in the interval, not just its two children, and both subtrees must be heaps on their own intervals. On a heap the two formulations agree, and quantifying over the interval makes the invariant easy to restrict to a subtree, exactly like LabelledTree.Ordered in Chapter 4.

Reading the Lean
  • The priority type α only needs ≤. The library uses it with WithTop Nat for next touches and with the order dual of WithBot Nat for last touches, below.
  • There is no tie-breaking rule. With equal priorities several shapes satisfy Heap, and every statement that uses it holds for all of them. The construction needs this freedom: once a key is never touched again its priority is ⊤, and many keys share it.
  • Every interval has a treap. The library proves it, for priorities in a linear order, by the textbook recursion: put a key of minimum priority at the root and recurse on both sides. The statement is Results.exists_tree, below.

32.2 Priorities from the future

Fix an arborally satisfied point set PP and a time tt. The priority of a key is the first time, at or after tt, at which PP touches it:

defGeometric.nextTouchpropext · Classical.choice · Quot.soundStructures/Treap/Abstract.lean:10
/-- First touch at or after `time`; infinity means that the key is never touchedagain. These priorities depend on the future and are used only offline. -/def nextTouch (P : Finset Point) (time key : Nat) : WithTop Nat :=  ((P.filter fun p => p.1 = key ∧ time ≤ p.2).image Prod.snd).min

The value is the minimum of the times of the points in column key at or after time, in WithTop Nat, so a key with no such point gets ⊤, read “never again”. This priority depends on the future of the execution, and the construction is offline for that reason alone.

Here is the invariant of the construction: before row tt is served, the tree is a treap for nextTouch P t. Its first consequence needs no geometry at all. A key touched at time tt has priority exactly tt, the smallest value any key can have at time tt. If xx is touched at time tt, every ancestor of xx has priority at most tt, so it is touched at time tt as well. The keys of row tt are therefore closed under taking ancestors: they form a rooted connected region at the top of the tree. A row of the point set is a legal step of the rooted-region model of Chapter 8.

The proof reads this region off the tree by descending from the root while the visited key is touched on the current row. It is the definition Region.project in Models/Region/Defs.lean. Like the next three definitions of this chapter, it belongs to the proof, not to any theorem statement, so the book describes it without quoting its Lean. project P time t lo turns t into a Region. A node whose key is touched at time becomes a region node, and the first untouched key on each branch closes the descent: its whole subtree becomes a hole, kept intact. On any tree, project returns a region whose tree is t again. On a next-touch treap it selects the whole row: the internal lemma Region.project_keys states that the active keys of the projection are exactly the keys touched at time in the interval. This is where the descent’s “stop at the first untouched key” is justified: below an untouched key nothing is touched on this row.

32.3 Rearranging the touched region

After row tt, only the priorities of touched keys change. An untouched key xx has nextTouch P (t+1) x = nextTouch P t x, because its next touch was already after tt. Every hole of the region is therefore still a treap for the new priorities, and it is enough to rearrange the region itself. Inside the region, the target order is heap order among its own nodes, Region.ActiveHeap: ActiveHeap priority s lo asks that every region node have priority at most that of every active key below it, ignoring the holes entirely. Any region can be rearranged into this order without changing its fringe: the internal lemma Region.heapify (in Models/Region/Heapify.lean) produces a region u with Region.Same s u lo and ActiveHeap priority u lo. It brings an active key of minimum priority to the top and recurses on both sides, with the holes riding along in inorder. Planning the rearrangement is free in the model; only the touched nodes are charged.

Heap order among the active nodes is not yet a treap. A rearranged node may now sit directly above a hole, and its new priority must not exceed the priorities inside that hole. This is the one place where arboral satisfaction enters:

defGeometric.RowAdjacentpropext · Classical.choice · Quot.soundStructures/Treap/Abstract.lean:23
/-- No other point on the current row lies between `a` and `b`. -/def RowAdjacent (P : Finset Point) (time a b : Nat) : Prop :=  ∀ x, (x, time) ∈ P → min a b ≤ x → x ≤ max a b → x = a

RowAdjacent P time a b says that no point of row time lies between a and b, except possibly at a itself. A hole of the region is a maximal interval of keys untouched at tt, and it hangs from one of the two touched keys that bound it. So every key bb of a hole is row-adjacent to its parent aa. The internal lemma adjacent_nextTouch (in Structures/Treap/Priorities.lean) then states:

If PP is arborally satisfied, (a,t)∈P(a, t) \in P, a≠ba \ne b, and aa and bb are row-adjacent at time tt, then nextTouch P (t+1) a ≤ nextTouch P (t+1) b.

The argument is short. Suppose bb is next touched at time f>tf > t. The rectangle spanned by (a,t)(a, t) and (b,f)(b, f) contains a third point of PP, and in an arborally satisfied set one can find such a point on one of the two sides through (a,t)(a, t). The bottom side is row tt between aa and bb, which adjacency rules out. So the point is in column aa, at a time in (t,f](t, f], and aa is touched again no later than bb.

With this lemma, Region.restore (in Structures/Treap/Restore.lean) shows that a region in active heap order, whose holes are treaps and whose keys are exactly the row, is a treap for time t+1t+1. The invariant is restored, and the next row is again the top region of the tree.

The whole construction

Take a treap for nextTouch P 0 on the nn keys; this is the initial tree, and the construction chooses it. For each row tt: project the row, which contains the request, rearrange it into heap order for time t+1t+1, and continue. Each step is a RegionStep charging the size of the row, so the total charge is exactly the number of points of PP. This is the forward direction of Results.ass_iff_region_execution. Serving each region on the pointer machine instead, by two applications of the reshaping lemma Results.reshape, costs at most 3333 instructions per touched node, which is Results.ass_to_pointers.

The figure runs the construction on the GreedyASS solution (Section 25.1) of a request sequence you choose. The point set is drawn below the tree with the same horizontal axis, so each column of points sits under its key. Steps alternate between highlighting the touched region of the current row and rearranging it. The hanging subtrees never change; only the highlighted nodes move.

Watch the priorities

Step through the whole sequence and check that the highlighted region is always at the top of the tree, and that it contains every point of the current row. Then pick a key whose next touch is far away and follow it: it sinks below the keys that will be needed sooner. Switch the priority labels to “last touch” and check that the same trees are also ordered by the past, most recent on top. The next section explains why.

The figure’s JavaScript port breaks priority ties by the smaller key, which is one of the choices Heap allows. Its test suite checks every invariant above on the GreedyASS point sets computed by Lean: heap order before and after each row, project returning exactly the row, unchanged fringes, the adjacency inequality, and a total charge equal to the number of points.

32.4 Priorities from the past

The converse direction starts from an arbitrary execution of the rooted-region model and must show that the touched nodes, row by row, form an arborally satisfied set. There is no future to consult, only the history. The proof uses two definitions from Models/Region/View/Defs.lean. lastTouch P key is the latest time at which the history P touches key, in WithBot Nat, and ⊥ if it never has. HistoryHeap P t says that t is a max-heap of last touches, with the most recently touched keys on top. It is stated with Geometric.Heap by reversing the order: OrderDual.toDual turns “minimum of the dual” into “maximum”. Keys never touched have priority ⊥, the bottom of the original order, so they sink below every touched key.

The invariant is maintained by every rooted-region step, whatever rearrangement it chooses:

  • Initially the history is empty, every key has priority ⊥, and every tree is a history heap.
  • A step touches a rooted region at the new time tt. Every key of the region now has last touch tt, the maximum, and the region is at the top of the tree. Its holes are untouched and keep their order. So any rearrangement of the region is again a history heap (region_history_heap, in Models/Region/View/Preservation.lean).

The invariant gives arboral satisfaction one row at a time. Let a=(x,s)a = (x, s) be an old point and b=(y,t)b = (y, t) a point of the new row, with x≠yx \ne y, so s<ts < t. The rooted region touched at time tt contains yy, so it also contains every ancestor of yy. The internal lemma between_ancestor finds a key cc of the region between xx and yy whose last touch is at least that of xx; on the tree, cc is the lowest common ancestor of xx and yy, which lies between them in inorder and above xx in the heap. If c≠yc \ne y, the point (c,t)(c, t) is a third point of the rectangle. If c=yc = y, then yy was last touched at some time in [s,t)[s, t), and that point lies on the rectangle’s side. Pairs inside the new row are degenerate, and pairs of old points were handled before. This is region_ass, and iterating it along a RegionExecution gives the backward direction of Results.ass_iff_region_execution, with exactly one point per touched node.

Reading the Lean

The two invariants describe the same trees in the treap construction. Before row tt, the tree is a min-heap of next touches and, by the argument above, a max-heap of last touches. The figure’s “last touch” labels show the second order on the trees built for the first. Keys touched recently and keys needed soon are near the root, and the construction of the previous section is one particular way of keeping both.

32.5 Where these definitions sit

The treap construction is the only offline argument of the geometric chapters. Its priorities come from the future of the point set, so it converts a whole solution, never a request at a time. The online direction, in Section 25.2, cannot know next touches and replaces the treap by last-touch supernodes stored in the split trees of Chapter 33.

32.6 Treaps for arbitrary priorities

Everything so far used treaps for one kind of priority, the next touches. Three classical facts hold for priorities in any linear order. They are stated in Structures/Treap/Order/Abstract.lean and are used by the random treaps of the next section. All three read a tree on the ranks lo, lo+1, …, lo + n - 1, as Geometric.Heap does.

Theorem (existence). For every priority function into a linear order, every interval of nn ranks has a treap of size nn. Ties are allowed.

theoremGeometric.TreapOrder.Results.exists_treepropext · Classical.choice · Quot.soundStructures/Treap/Order/Abstract.lean:9
/-- Every finite inorder interval has a treap for priorities in any linearorder. In particular priorities need not be next-touch times. -/theorem exists_tree {α : Type} [LinearOrder α] (priority : Nat → α) (n lo : Nat) :    ∃ t : Tree, t.size = n ∧ Heap priority t lo := heap_exists priority n lo

The proof is the recursion of the first section: a key of minimum priority is the root, and both sides are built recursively. The priorities can be anything, not only next-touch times.

Theorem (uniqueness). If the priorities are distinct on the interval, two treaps of the same size on it are the same tree.

theoremGeometric.TreapOrder.Results.unique_shapepropext · Classical.choice · Quot.soundStructures/Treap/Order/Abstract.lean:14
/-- Distinct priorities make that treap unique. -/theorem unique_shape {α : Type} [LinearOrder α] (priority : Nat → α)    (t u : Tree) (lo : Nat) (size : t.size = u.size)    (ht : Heap priority t lo) (hu : Heap priority u lo)    (unique : Set.InjOn priority (Set.Ico lo (lo + t.size))) : t = u :=  heap_unique priority t u lo size ht hu unique

Distinctness is needed only on the interval, Set.InjOn priority (Set.Ico lo (lo + t.size)). Keys outside it may share priorities.

Theorem (ancestors are interval minima). Let the priorities be distinct on the interval, and let aa and xx be two of its ranks. Then aa lies on the search path to xx exactly when aa has the smallest priority among all ranks between aa and xx, inclusive.

theoremGeometric.TreapOrder.Results.ancestor_minimumpropext · Classical.choice · Quot.soundStructures/Treap/Order/Abstract.lean:21
/-- The ancestor event is exactly an interval-minimum event. This deterministicidentity does not assume or assert a distribution on priorities. -/theorem ancestor_minimum {α : Type} [LinearOrder α] (priority : Nat → α)    (t : Tree) (lo a x : Nat) (heap : Heap priority t lo)    (unique : Set.InjOn priority (Set.Ico lo (lo + t.size)))    (ha : lo ≤ a ∧ a < lo + t.size) (hx : lo ≤ x ∧ x < lo + t.size) :    a ∈ t.searchPath lo x ↔      ∀ b, min a x ≤ b → b ≤ max a x → priority a ≤ priority b :=  heap_ancestor_iff priority t lo a x heap unique ha hx

The search path (Tree.searchPath) runs from the root to xx and includes both. So “on the search path to xx” means “an ancestor of xx, or xx itself”, and for a=xa = x both sides hold trivially. The proof follows the root, which has the minimum priority of the whole interval. If the root is aa, both sides hold. If the root is x≠ax \ne a, or lies strictly between aa and xx, both sides fail: aa is not on the path, and the root is a rank of the interval with a smaller priority than aa. Otherwise aa and xx lie in the same subtree, and the induction continues there. This is a deterministic identity, with no probability in it. It turns every ancestor event of a treap into an event about which key of an interval has the smallest priority.

32.7 Random treaps

Theorem 1 of the lazy finger paper (Bose et al. 2016) gives, for any positive weights, a randomized static tree in which, for every pair of keys x,yx, y, the expected cost of moving the lazy finger from xx to yy is within a constant factor of the weighted dynamic-finger charge of the pair. The library states it as Results.weighted_charge in Chapter 15. The random tree is a treap with random priorities, and this section defines the probability space. It lives in Structures/Treap/Random/Definitions/Abstract.lean and contains no measure theory: it is a finite weighted average over orders of the keys.

A random order replaces random priorities. The key listed first gets the smallest priority and becomes the root of the treap, and so on down the list.

defTreap.Random.IsOrderpropext · Classical.choice · Quot.soundStructures/Treap/Random/Definitions/Abstract.lean:10
/-- A sampled order contains every universe key exactly once. -/def IsOrder (s : Finset Nat) (xs : List Nat) : Prop :=  xs.Nodup ∧ xs.toFinset = s

IsOrder s xs says that xs lists every key of the finite set s exactly once.

defTreap.Random.averagepropext · Classical.choice · Quot.soundStructures/Treap/Random/Definitions/Abstract.lean:14
/-- Expectation over a random priority order on `s`: choose its next key withprobability proportional to its positive weight, remove it, and repeat.The sampled list runs from lowest to highest priority. This is an explicitfinite distribution; positivity is required by its probability theorems. -/noncomputable def average (w : Nat → ℝ) (s : Finset Nat) (f : List Nat → ℝ) : ℝ :=  if s = ∅ then f [] else    ∑ x ∈ s.attach, w x.1 / (∑ k ∈ s, w k) *      average w (s.erase x.1) (fun xs => f (x.1 :: xs))termination_by s.carddecreasing_by exact Finset.card_erase_lt_of_mem x.2

average w s f is the expected value of f xs when the order xs of s is drawn as follows. The first key is chosen from s with probability proportional to its weight, w(x)/∑k∈sw(k)w(x)/\sum_{k \in s} w(k). The rest of the order is drawn in the same way from the remaining keys. Written out, the order x1,…,xmx_1, \dots, x_m has probability

∏i=1mw(xi)w(xi)+w(xi+1)+⋯+w(xm), \prod_{i=1}^{m} \frac{w(x_i)}{w(x_i) + w(x_{i+1}) + \dots + w(x_m)} ,

which is sampling without replacement proportional to weight (the Plackett–Luce distribution). With equal weights every order has probability 1/m!1/m!. Equivalently, though the library never uses this, one may give the keys independent exponential priorities with rates w(x)w(x) and sort them increasingly.

To read a random treap off an order, use the position in the list as the priority, xs.idxOf. On a genuine order these positions are distinct (order_idxOf_injective), so by Results.unique_shape the order determines the treap. If T xs is a treap for xs.idxOf, then average w s (fun xs => g (T xs)) is the expectation of g over the random treap.

Reading the Lean
  • The definition is total. The empty set gives f [], and nothing in the definition requires positive weights. With nonpositive weights it is not an expectation. With total weight 00, Lean’s division by zero gives 00 for every term. The probability statements all assume 0 < w x on the set.
  • Under that hypothesis the proof files establish what an expectation should satisfy. The total probability is one (average_const), and the average is linear (average_add, average_mul, average_sum). It depends only on the values of f on genuine orders (average_congr, average_mono).
  • exists_order_le_average is the finite probabilistic method: some genuine order makes f at most its average. This turns the randomized tree into a deterministic one.
defTreap.Random.firstInpropext · Classical.choice · Quot.soundStructures/Treap/Random/Definitions/Abstract.lean:25
/-- First key of `s` in an order; `none` if the order contains no such key. -/def firstIn (s : Finset Nat) : List Nat → Option Nat  | [] => none  | x :: xs => if x ∈ s then some x else firstIn s xs
defTreap.Random.firstProbabilitypropext · Classical.choice · Quot.soundStructures/Treap/Random/Definitions/Abstract.lean:30
/-- Probability that `a` has minimum priority in `s`, when priorities aresampled over the whole universe `u`. -/noncomputable def firstProbability (w : Nat → ℝ) (u s : Finset Nat) (a : Nat) : ℝ :=  average w u (fun xs => if firstIn s xs = some a then 1 else 0)

firstIn s xs is the first key of s in the list xs, that is, the key of s with the smallest priority, or none if xs contains no key of s. firstProbability w u s a is the probability that a comes first among s when the whole universe u is ordered at random. The basic lemma is firstProbability_eq (in Random/Minimum.lean):

If the weights are positive on u, s ⊆ u and a ∈ s, then firstProbability w u s a =w(a)/∑k∈sw(k)= w(a) / \sum_{k \in s} w(k).

The keys outside s do not bias which key of s comes first. Combined with Results.ancestor_minimum, this gives the ancestor probabilities of a random treap. Let W[i,j]W[i, j] be the total weight of the ranks between ii and jj inclusive:

  • aa lies on the search path to xx with probability w(a)/W[min⁡(a,x),max⁡(a,x)]w(a) / W[\min(a, x), \max(a, x)] (exists_random_treap, in Random/Tree.lean);
  • aa lies on the search paths to both xx and yy with probability w(a)/W[min⁡(a,x,y),max⁡(a,x,y)]w(a) / W[\min(a, x, y), \max(a, x, y)] (common_ancestor_probability).

The lazy-finger distance between xx and yy counts the ancestors of xx and of yy that are not common ancestors. Summing these probabilities over aa gives the exact expected distance Results.expected_distance, and bounding the sums gives Results.weighted_charge. Both are in Chapter 15.

What the statements say about the trees

The two theorems of Chapter 15 assert that some family of trees T : List Nat → Tree, each of size nn, has the stated average. They do not say that T xs is a treap. The treap is the witness built in the proof, by exists_random_treap. Their statements depend on this chapter only through average, the distribution over orders.