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

Chapter 35 · Simulating fingers · Section 35.1BST deques and tendons

A finger in a binary search tree may sit far below the root. The pointer machine of Chapter 7 has a single cursor that starts at the root for every request, so to simulate a persistent finger it must reach the finger in a constant number of steps. The deep path from the root down to the finger must therefore be stored compactly. The finger hand of Section 35.2 does this, and this section provides its building blocks.

A tendon is a long path of a reference tree, from a top node down to a bottom node, together with the subtrees hanging off it. In inorder, the path nodes that are smaller than the bottom increase as the path descends, and the nodes that are larger decrease. A tendon therefore stores the path as two sorted sequences, each kept in a BST deque. A BST deque is a binary search tree in which both the minimum and the maximum sit at depth one. Nodes can be pushed or popped at either end by a constant number of pointer instructions, amortized. In the tendon the bottom of the path sits at physical depth at most four, however long the path is, and the path can grow or shrink by one node at either end in amortized constant work.

The vocabulary of hands, tendons and knuckles comes from Demaine, Iacono, Langerman and Özkan (2013), who simulate several fingers inside one BST. The library builds its own version of the construction, with explicit constants.

Do you need this section?

No theorem statement of the reading interface mentions a deque or a tendon. These definitions are used in the proof of Results.optimal (Chapter 16), the part of Lazy Finger Theorem 6 stating that a dynamic BST does as well as the best static tree with a lazy finger, up to a constant factor and a startup term. They are never on the reading path of a headline result. Read this section to follow that proof, or as an example of how the library argues about pointer-machine traces. All definitions are in Structures/BSTDeque and Structures/Tendon. The cost lemmas quoted below are in the proof files of the same directories.

35.1.1 Overview

All the structures of this section are Lazy.Skeletons (Chapter 7). A skeleton is a connected region of active nodes whose leaves are holes, each holding an entire subtree that the structure never enters. The holes of a deque are called its fringe, and their inorder list is all a deque guarantees about its contents. The deque has no keys of its own. Its elements are tree nodes, and their order is the inorder of the tree they sit in.

Costs are counted as pointer instructions (Pointer.Trace) from the root configuration of the structure’s tree to the root configuration of the result. Amortization uses an explicit potential, 3232 times the imbalance between the two halves of a deque. The bounds proved in the library are:

operation bound lemma
deque push at either end at most 22 instructions; potential grows by at most 3232 pushFront_trace, pushFront_potential
deque pop at either end instructions plus new potential at most 8080 plus old potential popFront_trace, popBack_trace
tendon: new node at the top at most 5454 instructions; amortized at most 8686 Tendon.State.addTop_trace, addTop_amortized
tendon: new node at the bottom amortized at most 134134 Tendon.State.addBottom_amortized
tendon: remove the top node amortized at most 132132 Tendon.State.removeTop
tendon: remove the bottom’s parent amortized at most 180180 Tendon.State.removeBottom

None of these constants depends on the size of the hanging subtrees or on the length of the path.

35.1.2 Deques of nodes

A deque is two stacks on either side of a pivot. The stack of small nodes is a right spine whose left children are fringe subtrees, and the stack of large nodes is the mirror image:

defBSTDeque.frontSpineno axiomsStructures/BSTDeque/Definitions/Abstract.lean:12
/-- A right spine whose left subtrees are untouched fringe trees. -/def frontSpine : List Tree → Tree → Skeleton  | [], gap => .hole gap  | g :: gs, gap => .node (.hole g) (frontSpine gs gap)
defBSTDeque.backSpineno axiomsStructures/BSTDeque/Definitions/Abstract.lean:17
/-- A left spine, stored from maximum to minimum. -/def backSpine : List Tree → Tree → Skeleton  | [], gap => .hole gap  | g :: gs, gap => .node (backSpine gs gap) (.hole g)

frontSpine [g₁, g₂, …] gap is a node with left hole g₁ whose right child is frontSpine [g₂, …] gap. The list ends in the hole gap at the bottom on the right. backSpine stores its list from the maximum inward, so its first node is the largest, with the right hole g₁.

inductiveBSTDeque.Dequeno axiomsStructures/BSTDeque/Definitions/Abstract.lean:22
/-- A pivot separates two stacks of active BST nodes. The holes contain arbitrarysubtrees; their nodes are neither traversed nor charged by deque operations. -/inductive Deque where  | empty (gap : Tree)  | node (front : List Tree) (leftGap rightGap : Tree) (back : List Tree)

A nonempty deque node front a b back is a pivot node whose left subtree is frontSpine front a and whose right subtree is backSpine back b. The holes a and b are the two fringe subtrees adjacent to the pivot. An empty deque empty gap has no active node and only one hole.

defBSTDeque.Deque.skeletonno axiomsStructures/BSTDeque/Definitions/Abstract.lean:30
def skeleton : Deque → Skeleton  | .empty gap => .hole gap  | .node front a b back => .node (frontSpine front a) (backSpine back b)
defBSTDeque.Deque.treeno axiomsStructures/BSTDeque/Definitions/Abstract.lean:34
def tree (q : Deque) : Tree := q.skeleton.tree
defBSTDeque.Deque.sizeno axiomsStructures/BSTDeque/Definitions/Abstract.lean:36
def size : Deque → Nat  | .empty _ => 0  | .node front _ _ back => front.length + 1 + back.length
defBSTDeque.Deque.fringeno axiomsStructures/BSTDeque/Definitions/Abstract.lean:40
/-- The complete inorder sequence of untouched fringe subtrees. -/def fringe : Deque → List Tree  | .empty gap => [gap]  | .node front a b back => front ++ [a, b] ++ back.reverse

For example, take front = [g₁, g₂] and back = [h₁, h₂], and name the front nodes n1,n2n_1, n_2, the pivot pp and the back nodes m1,m2m_1, m_2. The inorder sequence of the tree is

g1 n1 g2 n2 a  p  b m2 h2 m1 h1. g_1\ n_1\ g_2\ n_2\ a\ \ p\ \ b\ m_2\ h_2\ m_1\ h_1 .

The pivot is the root, the minimum n1n_1 is its left child and the maximum m1m_1 is its right child. In general the ii-th smallest front node is at depth ii, so a deque is fast only at its two ends. size counts the active nodes, front.length + 1 + back.length, and fringe lists the holes in inorder, front ++ [a, b] ++ back.reverse, one more than the size. The library proves skeleton.size = size and skeleton.fringe = fringe (in Shape.lean).

defBSTDeque.Deque.potentialno axiomsStructures/BSTDeque/Definitions/Abstract.lean:45
/-- Imbalance pays for occasional rebuilding when a stack becomes empty. -/def potential : Deque → Nat  | .empty _ => 0  | .node front _ _ back => 32 * Nat.dist front.length back.length
defBSTDeque.Deque.balanceno axiomsStructures/BSTDeque/Definitions/Abstract.lean:50
/-- Build a balanced pair of stacks from an inorder fringe sequence. The emptyinput is totalized; operations only rebuild nonempty sequences. -/def balance (xs : List Tree) : Deque :=  let k := (xs.length - 2) / 2  match xs.drop k with  | a :: b :: rest => .node (xs.take k) a b rest.reverse  | [a] => .empty a  | [] => .empty .nil

The potential is 32 ∣ ∣front∣−∣back∣ ∣32\,|\,|\mathit{front}| - |\mathit{back}|\,|. balance xs rebuilds a deque from a fringe list: the first k=⌊(∣xs∣−2)/2⌋k = \lfloor(|xs| - 2)/2\rfloor holes go to the front, the next two become a and b, and the rest go to the back, reversed. Both stacks then have nearly equal length, and balance_potential proves that the result has potential at most 3232. On a one-element list balance returns an empty deque. The empty list is totalized to empty .nil, a case the operations never reach.

35.1.3 Pushing and popping

defBSTDeque.Deque.pushFrontno axiomsStructures/BSTDeque/Definitions/Abstract.lean:59
/-- The new minimum is initially supplied as the parent of the deque, with `g`as its left subtree. -/def pushFront (g : Tree) : Deque → Deque  | .empty a => .node [] g a []  | .node front a b back => .node (g :: front) a b back
defBSTDeque.Deque.pushBackno axiomsStructures/BSTDeque/Definitions/Abstract.lean:65
/-- The new maximum is initially supplied as the parent of the deque. -/def pushBack (g : Tree) : Deque → Deque  | .empty a => .node [] a g []  | .node front a b back => .node front a b (g :: back)
defBSTDeque.Deque.popFrontno axiomsStructures/BSTDeque/Definitions/Abstract.lean:70
/-- Expose the minimum as a parent of the remaining deque, returning its leftfringe subtree. No tree node is deleted by the realizing pointer trace. -/def popFront : Deque → Option (Tree × Deque)  | .empty _ => none  | .node (g :: gs) a b back => some (g, .node gs a b back)  | .node [] a b back => some (a, balance (b :: back.reverse))
defBSTDeque.Deque.popBackno axiomsStructures/BSTDeque/Definitions/Abstract.lean:77
/-- Expose the maximum as a parent, returning its right fringe subtree. -/def popBack : Deque → Option (Tree × Deque)  | .empty _ => none  | .node front a b (g :: gs) => some (g, .node front a b gs)  | .node front a b [] => some (b, balance (front ++ [a]))

The node being pushed comes from the enclosing structure. Before pushFront g, the new node is the parent of the deque, with left subtree g and the deque as its right subtree. In the tree .node g q.tree it is the root, and it is smaller than every node of the deque. Two instructions, downRight and rotateRightChild, rotate the pivot above it, and the new node becomes the first node of the front spine (pushFront_trace). Pushing onto an empty deque costs nothing: the tree .node g a already has the shape of .node [] g a [].

A pop exposes the minimum as the parent of the remaining deque and returns its left hole. When the front stack is nonempty, its first node is the pivot’s left child, and downLeft, rotateLeftChild bring it to the root. When the front stack is empty, the pivot itself is the minimum. popFront then rebuilds the rest with balance, and the proof realizes the change of shape by the reshaping theorem Results.reshape, at most 1616 instructions per node. That linear cost is paid by the old potential: the back stack has as many nodes as the imbalance it creates. The result is popFront_trace:

If q.popFront = some (g, r), a pointer trace of kk instructions turns q.tree into .node g r.tree, root to root, with k+Φ(r)≤80+Φ(q)k + \Phi(r) \le 80 + \Phi(q).

No node is deleted. A pop does not remove anything from the tree; it only changes which node the deque regards as its own. The popped node stays as the root, and the enclosing structure takes it over.

35.1.3.1 Operations and programs

The library also packages these operations as a typed vocabulary:

inductiveBSTDeque.Operationno axiomsStructures/BSTDeque/Definitions/Abstract.lean:85
/-- A legal deque operation. Pushes receive a node from the enclosing structure;pops return one to it. The indices record the resulting deque state. -/inductive Operation : Deque → Deque → Type where  | pushFront (g : Tree) (q : Deque) : Operation q (q.pushFront g)  | pushBack (g : Tree) (q : Deque) : Operation q (q.pushBack g)  | popFront (q r : Deque) (g : Tree) (h : q.popFront = some (g, r)) : Operation q r  | popBack (q r : Deque) (g : Tree) (h : q.popBack = some (g, r)) : Operation q r
defBSTDeque.Operation.inputno axiomsStructures/BSTDeque/Definitions/Abstract.lean:95
/-- Tree supplied by the caller at the operation boundary. -/def input {q r : Deque} : Operation q r → Tree  | .pushFront g q => .node g q.tree  | .pushBack g q => .node q.tree g  | .popFront q _ _ _ => q.tree  | .popBack q _ _ _ => q.tree
defBSTDeque.Operation.outputno axiomsStructures/BSTDeque/Definitions/Abstract.lean:102
/-- Tree returned at the boundary. A popped node remains as its root. -/def output {q r : Deque} : Operation q r → Tree  | .pushFront g q => (q.pushFront g).tree  | .pushBack g q => (q.pushBack g).tree  | .popFront _ r g _ => .node g r.tree  | .popBack _ r g _ => .node r.tree g
defBSTDeque.Operation.Realizesno axiomsStructures/BSTDeque/Definitions/Abstract.lean:109
def Realizes {q r : Deque} (op : Operation q r) (cost : Nat) : Prop :=  Pointer.Trace ⟨op.input, []⟩ ⟨op.output, []⟩ cost

An Operation q r is a legal operation taking deque q to deque r. Pops carry a proof that they succeed, so popping an empty deque is not an operation. input and output are the trees at the boundary: a push receives its node as the root above the deque, and a pop leaves its node as the root above the result. Realizes op cost says that a pointer trace of exactly cost instructions goes from the input to the output, root to root.

inductiveBSTDeque.Programno axiomsStructures/BSTDeque/Definitions/Abstract.lean:114
/-- Any legal finite sequence, including arbitrary mixtures of both ends. -/inductive Program : Deque → Deque → Nat → Type where  | nil (q : Deque) : Program q q 0  | cons {q r s : Deque} {n : Nat} (op : Operation q r) (rest : Program r s n) :      Program q s (n + 1)
inductiveBSTDeque.Program.Realizesno axiomsStructures/BSTDeque/Definitions/Abstract.lean:120
/-- A pointer realization of each operation at its stated input/output boundary.The caller's transfer of nodes between boundaries is separate from this cost. -/inductive Program.Realizes : {q r : Deque} → {n : Nat} → Program q r n → Nat → Prop where  | nil (q : Deque) : Realizes (.nil q) 0  | cons {q r s : Deque} {n k m : Nat} {op : Operation q r} {rest : Program r s n}      (first : op.Realizes k) (tail : rest.Realizes m) :      Realizes (.cons op rest) (k + m)

A Program q s n is a sequence of n operations, mixing both ends arbitrarily, from q to s. Program.Realizes adds up the realizations of its operations. Moving a node between the deque and its caller, between two operations, is the caller’s business and is not part of this cost.

Vocabulary without a theorem

At present no theorem of the library mentions Operation.Realizes or Program.Realizes. The per-operation bounds are proved directly on the trees, in pushFront_trace, pushBack_trace, popFront_trace and popBack_trace (in Structures/BSTDeque/Operations.lean), and the tendons below use those. Summing these bounds would show that every program of nn operations from a deque of potential Φ\Phi is realizable with at most 80n+Φ80n + \Phi instructions, but the library does not state this.

35.1.4 The two boundary slots

A tendon grafts its bottom subtree into the extreme holes of its deques. These are the leftmost and rightmost fringe slots:

defBSTDeque.Deque.minGapno axiomsStructures/BSTDeque/Boundary/Definitions/Abstract.lean:8
def minGap : Deque → Tree  | .empty g => g  | .node [] a _ _ => a  | .node (g :: _) _ _ _ => g
defBSTDeque.Deque.maxGapno axiomsStructures/BSTDeque/Boundary/Definitions/Abstract.lean:13
def maxGap : Deque → Tree  | .empty g => g  | .node _ _ b [] => b  | .node _ _ _ (g :: _) => g
defBSTDeque.Deque.withMinno axiomsStructures/BSTDeque/Boundary/Definitions/Abstract.lean:18
/-- Change only the boundary hole, leaving every active node in place. -/def withMin (q : Deque) (g : Tree) : Deque :=  match q with  | .empty _ => .empty g  | .node [] _ b back => .node [] g b back  | .node (_ :: gs) a b back => .node (g :: gs) a b back
defBSTDeque.Deque.withMaxno axiomsStructures/BSTDeque/Boundary/Definitions/Abstract.lean:25
def withMax (q : Deque) (g : Tree) : Deque :=  match q with  | .empty _ => .empty g  | .node front a _ [] => .node front a g []  | .node front a b (_ :: gs) => .node front a b (g :: gs)

minGap is the first hole in inorder, the left hole of the minimum, or the hole a when the front stack is empty. withMin q g replaces that one hole by g, without moving any active node. maxGap and withMax are the mirror images. The proof files show that withMin and withMax change neither the size nor the potential, and only the extreme entry of the fringe.

defBSTDeque.Deque.minContextno axiomsStructures/BSTDeque/Boundary/Definitions/Abstract.lean:31
/-- Context of the minimum-side fringe slot, at distance at most two. -/def minContext : Deque → List Pointer.Frame  | .empty _ => []  | .node [] _ b back => [.left (backSpine back b).tree]  | .node (_ :: gs) a b back =>      [.left (frontSpine gs a).tree, .left (backSpine back b).tree]
defBSTDeque.Deque.maxContextno axiomsStructures/BSTDeque/Boundary/Definitions/Abstract.lean:38
/-- Context of the maximum-side fringe slot, at distance at most two. -/def maxContext : Deque → List Pointer.Frame  | .empty _ => []  | .node front a _ [] => [.right (frontSpine front a).tree]  | .node front a b (_ :: gs) =>      [.right (backSpine gs b).tree, .right (frontSpine front a).tree]

minContext q is the zipper path (Pointer.Frame, innermost first) from the minimum slot up to the root of the deque, and maxContext the path from the maximum slot. Each has at most two frames, because the extreme nodes are at depth one. The library proves that plugging the slot’s contents back in gives the deque’s tree, Pointer.plug q.minContext q.minGap = q.tree, and that the offset of the minimum slot is 00. A subtree grafted into a boundary slot is therefore reachable from the deque’s root in at most two moves.

35.1.5 Tendons

A tendon represents a path of the reference tree, given as a zipper path cs, innermost first: cs.head is the frame of the bottom node’s parent. A frame .right l is an ancestor smaller than the bottom subtree, whose left subtree l hangs off the path; a frame .left r is a larger ancestor with hanging right subtree r. The subtrees hanging on each side, in inorder, are:

defTendon.lowerFringeno axiomsStructures/Tendon/Definitions/Abstract.lean:10
/-- Side subtrees before the bottom endpoint, in inorder. The reference pathuses the same innermost-first convention as the pointer-machine zipper. -/def lowerFringe : List Pointer.Frame → List Tree  | [] => []  | .left _ :: cs => lowerFringe cs  | .right l :: cs => lowerFringe cs ++ [l]
defTendon.upperFringeno axiomsStructures/Tendon/Definitions/Abstract.lean:17
/-- Side subtrees after the bottom endpoint, in inorder. -/def upperFringe : List Pointer.Frame → List Tree  | [] => []  | .left r :: cs => r :: upperFringe cs  | .right _ :: cs => upperFringe cs

lowerFringe cs lists the hanging subtrees that precede the bottom in inorder, from the top of the path down to the bottom, and upperFringe cs those that follow it, from the bottom up. Both orders are inorder. The path itself is not stored in this form: only the two sides are, and their interleaving along the path is lost.

structureTendon.Stateno axiomsStructures/Tendon/Definitions/Abstract.lean:23
/-- The endpoint is grafted into the maximum slot of the lower deque and theminimum slot of the upper deque. The stored values of these two slots are ignored. -/structure State where  lower : BSTDeque.Deque  upper : BSTDeque.Deque

A tendon state is a pair of deques. lower holds the path nodes smaller than the bottom and upper those larger than it. The bottom subtree is grafted into the maximum slot of lower and the minimum slot of upper, so the values stored in these two slots are placeholders.

defTendon.State.contextno axiomsStructures/Tendon/Definitions/Abstract.lean:31
def context (d : State) : List Pointer.Frame := d.upper.minContext ++ d.lower.maxContext
defTendon.State.treeno axiomsStructures/Tendon/Definitions/Abstract.lean:33
def tree (d : State) (bottom : Tree) : Tree := Pointer.plug d.context bottom
defTendon.State.skeletonno axiomsStructures/Tendon/Definitions/Abstract.lean:35
/-- The complete active tendon region, with the endpoint subtree left opaque. -/def skeleton (d : State) (bottom : Tree) : Skeleton :=  d.lower.skeleton.fillMax (d.upper.skeleton.fillMin (.hole bottom))

d.tree bottom is the physical tree. The bottom subtree goes into the minimum slot of the upper deque, and that whole deque goes into the maximum slot of the lower deque. The root is the lower deque’s pivot. context is the zipper path of the bottom: at most two frames in the upper deque, then at most two in the lower deque. So the bottom is at depth at most four, whatever the length of the path (context_length). skeleton is the same tree as a skeleton whose active nodes are exactly the path nodes, with bottom left as a hole.

defTendon.State.potentialno axiomsStructures/Tendon/Definitions/Abstract.lean:39
def potential (d : State) : Nat := d.lower.potential + d.upper.potential
defTendon.State.Representsno axiomsStructures/Tendon/Definitions/Abstract.lean:41
/-- A path representation retains every side subtree on its proper side of theendpoint. Interleaving is recorded by the reference path, not inferred from keys. -/def Represents (d : State) (cs : List Pointer.Frame) : Prop :=  d.lower.fringe.dropLast = lowerFringe cs ∧ d.upper.fringe.tail = upperFringe cs

Represents d cs is the representation invariant. The lower deque’s fringe, without its last slot, is lowerFringe cs, and the upper deque’s fringe, without its first slot, is upperFringe cs. So the deques have exactly as many nodes as the path has smaller and larger ancestors. The physical tree has the same nodes, in the same inorder, as the path itself, and the bottom subtree keeps its global rank (represents_offset). The shape inside each deque is arbitrary, which is what lets the operations work lazily. The reference path cs is not recoverable from d, since the deques do not record how the two sides interleave. Whoever needs cs, such as the finger hand, keeps it as separate bookkeeping.

defTendon.State.ofPathno axiomsStructures/Tendon/Definitions/Abstract.lean:46
/-- A balanced initial representation of any concrete reference path. -/def ofPath (cs : List Pointer.Frame) : State :=  ⟨BSTDeque.Deque.balance (lowerFringe cs ++ [.nil]),    BSTDeque.Deque.balance (.nil :: upperFringe cs)⟩

ofPath cs is a balanced representation of a path, built with balance from the two fringe lists, with .nil as the placeholder slot values. It represents cs and has potential at most 6464.

35.1.5.1 Growing and shrinking a tendon

defTendon.State.addTopno axiomsStructures/Tendon/Definitions/Abstract.lean:51
/-- Absorb the former top endpoint into the appropriate deque. The suppliedframe contains its off-path subtree. -/def addTop (d : State) : Pointer.Frame → State  | .right g => ⟨d.lower.pushFront g, d.upper⟩  | .left g => ⟨d.lower, d.upper.pushBack g⟩
defTendon.State.addBottomno axiomsStructures/Tendon/Definitions/Abstract.lean:57
/-- Absorb the bottom's former parent. Its off-path subtree replaces the openslot before the node is appended to the appropriate monotone component. -/def addBottom (d : State) : Pointer.Frame → State  | .right g => ⟨(d.lower.withMax g).pushBack .nil, d.upper⟩  | .left g => ⟨d.lower, (d.upper.withMin g).pushFront .nil⟩

addTop d f extends the path upward by the node whose frame is f. Before, that node is the parent of the tendon’s tree; after, it is part of the tendon. A smaller node (.right g) becomes the new minimum of the lower deque, and a larger node (.left g) the new maximum of the upper deque. The upper deque sits inside the lower one, so reaching its maximum first takes a short exchange: the lemma lower_exchange reshapes the at most three nodes around the lower deque’s maximum slot, at most 4848 instructions. addTop_represents proves that the result represents cs ++ [f], and addTop_trace that the whole update takes at most 5454 instructions.

addBottom d f extends the path at the other end. Here the old bottom node joins the tendon, and one of its children becomes the new bottom. Its hanging subtree g fills the slot that the bottom used to occupy (withMax g or withMin g), and the node is pushed as the new innermost element with a fresh placeholder slot. The result represents f :: cs, at amortized cost at most 134134.

The reverse operations are proved as lemmas. They have no definitions of their own, because the resulting state is produced by the proof:

  • removeTop: if d represents cs ++ [f], some e represents cs, and the top node is expelled to become the root above the tendon, Pointer.plug [f] (e.tree bottom), at amortized cost at most 132132.
  • removeBottom: if d represents f :: cs, some e represents cs, and the bottom’s parent leaves the tendon to become the new bottom endpoint, e.tree (Pointer.plug [f] bottom), at amortized cost at most 180180.

All four operations touch only the extreme slots of the deques and the at most four frames above the bottom. The rest of the path and every hanging subtree stay in place.

35.1.6 Where tendons are used

In a finger hand (Section 35.2), every edge of the compressed skeleton of the fingers is a tendon. When a finger moves, a skeleton vertex may need to appear in the middle of a tendon or disappear into one. The operations above perform these changes at the ends of the tendon, and the potentials of all tendons together pay for the occasional rebalancing.