Skip to main content
🧙‍♂️ Kris Kowal 🐘 🐙 🧛 📌 📬 Book Store

Weight Watching Splay Trees

A watercolor balance scale whose beam is a small binary tree of round discs, ochre and indigo, the heavier left branch hanging lower than the right, each disc with a blank paper tag on a thread and the top disc on the pivot ringed in red.

This is about a useful complication to the Sleator–Tarjan splay tree [1] that allows a sorted collection to emit the same change events as the equivalent sorted array (added this value at that index, removed that value from this index) without the cost of shifting a very large array.

The splay tree is the sorted set in my collections library. I added the complication in October of 2012, in the commit that implemented index tracking [2], so that a sorted set could give every content change an index, which is what you need to bind those changes to an array, or to an array that shows a window onto part of the set. An array that mirrors a sorted set has to shift everything after the point of every insertion and deletion, and I wanted the set itself to pay only logarithmic time for the same news. The code I link to is the library as it stands, at c785549 [3].

Also as a paper (PDF), with the same figures as line art.

Where the splay came from #

My first splay tree was not this one. The day I started collections, in July of 2012, I wrote a splay set with parent pointers [4], and it followed the splay tree that Fedor Indutny had written two weeks before, in callgrind.js [5]. His nodes kept their parents with setLeft and setRight, his search remembered the last node it passed, and he splayed from the bottom up, a zig, a zig-zig or a zig-zag at a time. Mine did all of that, and its rotations were his, case for case and statement for statement. An hour later, I rewrote it without parent pointers [6], as the simplified top-down splay, after the splay tree that Paolo Fragomeni had adapted from V8's for his forest [7], which came from the JavaScript splay tree in V8's tick processor [8]. The README [9] credited both, and said that I favored the second because it needs no parent references. Nothing of Fedor's code is left in the sorted set: the top-down splay replaced it within the hour. But that is where the library began. Neither of them kept weights.

The premise #

Every node in the tree carries a weight: the number of nodes in its subtree, itself included. The code calls it length. The code keeps it with touch, which recomputes a node's weight from its children's weights, and also notes the weight of the left child as the node's index. The whole difficulty, below, is calling touch on the right nodes in the right order.

Listing 1. touch, sorted-set.js lines 599 to 604

Node.prototype.touch = function () {
  this.length = 1 +
        (this.left ? this.left.length : 0) +
        (this.right ? this.right.length : 0);
  this.index = this.left ? this.left.length : 0;
};
A binary search tree of eleven letters with J at the root, ringed in red, weight 11. Its left subtree, rooted at D with weight 4, holds B, D, F and H; its right subtree, rooted at P with weight 6, holds M, N, P, S, T and V. Below, the sorted array B D F H J M N P S T V with indexes 0 through 10, J's cell at index 4 outlined in red.
Figure 1. J at the root. Its index is the weight of its left subtree: 4.

The premise is that the index of any node in the equivalent sorted array is the weight of its left subtree, when that node is at the root of the tree. Every key less than the root is in its left subtree, and every key greater is in its right. Here J is at the root, and its left subtree, at D, weighs 4: B, D, F and H. So J is at index 4. In the figures, each node's weight is in the tag above it, and the node that the step is about is ringed in red.

None of this is new. Sleator and Tarjan say, in the paper that introduced the splay tree, that a binary search tree can answer to positions as well as to keys if each node stores the number of its descendants, or the size of its left subtree, with the size of the whole tree in a header [1, p. 654]. Weight-balanced trees, Nievergelt and Reingold's trees of bounded balance, keep the same counts in every node, and balance on them [10]. Haskell's Data.Map is one, and its lookupIndex walks down from the root adding up the sizes of the left subtrees it passes [11]. A balanced tree updates its counts in its rotations, from the bottom up, and so can a splay tree that splays from the bottom up: Sleator and Tarjan point out that a rotation can carry any updating of auxiliary fields with it [1, p. 667]. The splay that this library uses works from the top down, and that is where it gets interesting.

A splay tree is a binary search tree that only ever works at its root. Every operation, looking up, adding or deleting a key, begins by splaying the tree for that key: rotating it until the key, or the nearest key to it, is at the root. So once a splay is done, the index is right there. indexOf splays for the value and, if the root holds it, returns the root's index.

Listing 2. indexOf, sorted-set.js lines 155 to 163

SortedSet.prototype.indexOf = function (value) {
  if (this.root) {
    this.splay(value);
    if (this.contentEquals(value, this.root.value)) {
      return this.root.index;
    }
  }
  return -1;
};

Sleator and Tarjan's splay does not keep subtree weights, but it can keep them trivially, with one exception: it must track its path through the tree, and roll up the weight changes along that path on the way out. The rest of this is about that exception.

Splaying from the top down #

The library uses the simplified top-down splay from Sleator and Tarjan's "Self-Adjusting Binary Search Trees" [1, p. 669]. It walks down from the root toward the key, and it takes the tree apart as it goes. Everything it passes that is less than the key goes into a left tree, L, and everything greater goes into a right tree, R. What remains below, the middle tree, still holds the key, if the tree holds it at all. When the walk ends, the node it ends on becomes the root, with L as its left subtree and R as its right. The simplified splay differs from the full one only at a zig-zag, where it links one node instead of two [1, p. 669]. Like Guibas and Sedgewick's one-pass balanced trees [12], it restructures on the way down, and never has to come back up, which is just the trouble with keeping weights.

The code hangs both L and R from a single stub node, a trick it borrows from V8's splay tree [13]: L is the stub's right child and R is its left, so L and R are never empty and there are no special cases. It keeps a pointer to the tail of each, the node on which the next one will hang: left is the last node of L, whose right child is next, and right is the last node of R, whose left child is next. Beside the stub, it makes one more empty node, history, which comes into the story below.

Listing 3. splay, sorted-set.js lines 343 to 352

  stub = left = right = new this.Node();
    // The history is an upside down tree used to propagate new tree sizes back
    // up the left and right arms of a traversal.  The right children of the
    // transitive left side of the tree will be former roots while linking
    // left.  The left children of the transitive walk to the right side of the
    // history tree will all be previous roots from linking right.  The last
    // node of the left and right traversal will each become a child of the new
    // root.
  history = new this.Node();
  root = this.root;
The tree that adding S, M, N, T, J, H, F, P, V, D and B in that order leaves. From B at the root, weight 11, a path runs right through D (10) and F (9) to T (8), whose right child is V (1). T's left child P (6) has S (1) on its right and H (4) on its left; H's right child N (3) has M (2) on its left, and M's left child J (1), ringed in red, is the key sought, eight levels down.
Figure 2. The tree that the eleven adds leave, with J, the key we want, eight levels down.

Adding S, M, N, T, J, H, F, P, V, D and B, in that order, leaves this tree. Each add splays the tree for the new key, so the order of the adds decides the shape. Let us look for J.

Rotations, and the weights they keep #

Each turn of the loop looks at the root of the middle tree and, if the key is not there, at the child in the key's direction.

The first turn of the splay. J is greater than B and greater than B's right child D, so the splay rotates left: D, ringed, rises to the top with weight 11, and B, ringed, becomes D's left child with weight 1. J, ringed, is still at the bottom; the rest of the tree is as before.
Figure 3. A zig-zig: the splay rotates left, and D comes up over B.

When the key is beyond both, in the same direction, that is a zig-zig, and the splay first rotates. J is greater than B and greater than D, so it rotates left: D comes up and B goes down to be D's left child. A rotation keeps both nodes' subtrees whole beneath them, so the code touches the lower node and then the upper, and their weights are exact: B is 1, and D is 11, the whole tree.

Listing 4. splay, sorted-set.js lines 388 to 406

    } else if (comparison > 0) {
      if (root.right) {
        if (this.contentCompare(value, root.right.value) > 0) {
                    // rotate left
                    //        Root         L(temp)
                    //      /     \       / \
                    //     L(temp) R    LL    Root
                    //    / \                /    \
                    //  LL   LR            LR      R
          temp = root.right;
          root.right = temp.left;
          root.touch();
          temp.left = root;
          temp.touch();
          root = temp;
          if (!root.right) {
            break;
          }
        }
After the first link. D and its left child B form the L tree, in ochre, hanging from a box marked L. D's tag is dashed and reads 11, though only two nodes are under it in L. A short dashed hook on D's right marks where the next node of L will hang. The middle tree, rooted at F with weight 9, still holds J, ringed in red. Below the tree, a grey box marked history has one ochre record, a small square in D's column, with a dashed line up to D.
Figure 4. The first link: D joins L, and the history takes its first record.

Then it links. D, which is less than J, joins L, with everything to its left, and the walk goes on into D's right child, F, which becomes the root of the middle tree. Here is the first sign of trouble. D's weight still says 11, but only B and D are under it in L. In the figures, a weight in a dashed tag is stale: it no longer counts what is drawn beneath it. The code does touch the old tail when it links a new one, but that only helps so much: the new tail's child is still the whole middle tree, which the splay has not finished taking apart.

So before it links, the splay remembers the node. It makes a record, a bare node of its own, whose left holds D, and pushes it onto a stack threaded through the records' right pointers, with history.right at the top. Below the tree, from here on, the figures draw the history: its stub, in grey, and each record as a small square in the column of the node it holds, with a dashed line up to that node.

Listing 5. splay, sorted-set.js lines 407 to 416

                // remember former root for repropagating length
        temp = new Node();
        temp.left = root;
        temp.right = history.right;
        history.right = temp;
                // link right
        left.right = root;
        left.touch();
        left = root;
        root = root.right;
J is greater than F but less than F's right child T, so F joins the L tree alone, as D's right child, joined to it by a thick ochre stroke. D's dashed tag still reads 11 and F's dashed tag reads 9. The middle tree is now rooted at T, weight 8, with J ringed at its bottom. In the history below, a second ochre record, for F, has been pushed between the history box and D's record, so the chain of records rises from the box up and to the left, the mirror of the L chain.
Figure 5. A zig-zag: F joins L alone.

When the key is beyond the root in one direction and short of the child in that direction, that is a zig-zag. The simplified splay does not rotate for a zig-zag. It links the root alone and goes on, and the next turn links in the other direction. J is greater than F but less than T, so F joins L, hanging from D's right, and the middle tree is T's. F's weight is 9 and D's is 11, both counting the middle tree. F's record goes on top of D's, so the newest record is nearest the stub. Drawn that way, the chain of records rises up and to the left from the stub, the mirror image of the chain it records, D and F going down and to the right in L.

J is less than T and less than T's left child P, a zig-zig: the splay rotates right, raising P over T, and links P into the R tree, in indigo, under a box marked R. P's dashed tag reads 8; beneath it in R are only T (3) and T's children S (1) and V (1), whose weights are exact. A dashed hook on P's left marks where the next node of R will hang. The middle tree is H (4), N (3), M (2) and J (1), ringed. In the history, an indigo record for P now hangs on the box's other side, rising to the right.
Figure 6. A zig-zig the other way: P rotates up over T and joins R.

J is less than T and less than P: a zig-zig to the left. The splay rotates right, raising P over T, so T is exact at 3 and P is exact at 8, and then links P into R. P's 8 still counts H and everything under it, which go on as the middle tree. Linking into R pushes onto the other stack: a record whose right holds P, threaded through the records' left pointers from history.left.

Listing 6. splay, sorted-set.js lines 375 to 384

                // remember former root for repropagating length
        temp = new Node();
        temp.right = root;
        temp.left = history.left;
        history.left = temp;
                // link left
        right.left = root;
        right.touch();
        right = root;
        root = root.left;
J is greater than H but less than H's right child N, a zig-zag: H joins the L tree as F's right child. F's dashed tag now reads 5 and H's reads 4. The R tree is unchanged, and the middle tree is N (3), M (2) and J (1), ringed. The history's ochre chain now holds three records, H nearest the box, then F, then D.
Figure 7. Another zig-zag: H joins L, and its record goes on top of that stack.

J is greater than H but less than N: another zig-zag, and H joins L. Linking H touches F, the old tail, which now weighs 5: itself, and H's 4, which is stale. H's record goes on top of the L stack.

J is less than N and less than N's left child M, a zig-zig: the splay rotates right, raising M over N, and links M into the R tree as P's left child. M's dashed tag reads 3, still counting J, and P's dashed tag reads 7. J, ringed, is alone in the middle with no children. The history holds three ochre records, H, F and D, and two indigo records, M nearest the box and then P, each with a dashed line up to its node.
Figure 8. M joins R, and J is alone in the middle.

J is less than N and less than M: a zig-zig, a rotation that raises M over N, and a link that hangs M from P. That touches P, the old tail of R, at 7. M's record goes on top of the R stack. J is now alone in the middle, and the walk is over.

At this point the nodes the walk linked make a chain down each side: D, F and H down the right edge of L, P and M down the left edge of R. Every node on those chains has a stale weight, because each was weighed when its child was still the whole middle tree. And the history holds the same two chains, upside down: from the stub, H, F and D up one side, and M and P up the other. The code's comment calls history an upside down tree, and so it is.

Reassembly, and the roll-up #

Reassembly. J, ringed, becomes the root, with the L tree, D, B, F and H in ochre, as its left subtree and the R tree, P, M, N, T, S and V in indigo, as its right. The two tails, H (1) and M (2), have just been touched and are exact. D (11), F (5), P (7) and J itself (1) still have dashed, stale tags. Below, the history still holds all five records.
Figure 9. Reassembly: J takes L and R, and every record is still waiting.

Reassembly gives the tail of L the middle root's left subtree, and the tail of R its right subtree, and touches both tails, so H and M are exact. Then J takes L and R as its own children. But D, F and P are still wrong, and so is J.

Listing 7. splay, sorted-set.js lines 425 to 431

    // reassemble
  left.right = root.left;
  left.touch();
  right.left = root.right;
  right.touch();
  root.left = stub.right;
  root.right = stub.left;

A node's weight depends on its children's, so the fix has to start at the tails and work up toward the root. The splay tree has no parent pointers, and L and R were built from the top down, so there is no way back up them. The history is the way back. Each stack holds its chain's nodes in the reverse of the order they were linked, so popping it visits the chain from the tail back to the top.

The roll-up through the R side: the splay touches M and then P, both ringed, in the reverse of the order they were linked. P's weight is now 6. D, F and J still have dashed, stale tags. Below, the two indigo records are popped, dashed and empty, numbered 1 for M and 2 for P; the three ochre records remain.
Figure 10. The roll-up pops the R stack, touching M, then P.

The roll-up pops the R stack first: it touches the node in the top record, M, and drops the record, then touches P, and drops that one. Each node is touched after the nodes beneath it, so each sees its children's exact weights. P is 6. In the figures, a popped record stays where it was, dashed and empty, numbered in the order in which the roll-up touched its node.

Listing 8. splay, sorted-set.js lines 433 to 437

    // propagate new lengths
  while (history.left) {
    history.left.right.touch();
    history.left = history.left.left;
  }
The roll-up through the L side: H, F and D, ringed, are touched in that order, from the bottom up. F is now 2 and D is now 4. Only J's tag, at the root, is still dashed. Below, every record is popped: 1 and 2 on the indigo side, and 3, 4 and 5 for H, F and D on the ochre side.
Figure 11. Then the L stack: H, F, then D.

Then the L stack: H, F, and D, which is 4.

Listing 9. splay, sorted-set.js lines 438 to 441

  while (history.right) {
    history.right.left.touch();
    history.right = history.right.right;
  }
The splay is done. J, ringed, is the root with weight 11; its left subtree, D, weighs 4, and its right subtree, P, weighs 6. Every tag is solid.
Figure 12. Done: J at the root, at index 4, with every weight true.

Last, the splay touches the new root. J weighs 11, and its index is the weight of D, 4: the first figure, again. The tail of each chain gets touched twice, once in reassembly and once at the top of its stack, which costs nothing but a moment. None of the stale weights is ever read before the roll-up replaces it.

Listing 10. splay, sorted-set.js lines 442 to 445

  root.touch();

  this.root = root;
};

Without the weights, a top-down splay never needs to look back up its path. With them, it does, and the two stacks are the price: one small record for every node the walk links, dropped when the splay returns. The splay is still logarithmic in amortized time, and the roll-up only retraces the same path.

Adding #

Adding K. The splay for K stops at M, ringed, now the root with weight 11, the nearest key above K, since K is not in the tree. M's left subtree, J with weight 5, holds the five keys less than K: B, D, F, H and J. A dashed red circle beside M marks where K will go. Below, the array B D F H J M N P S T V, with a dashed gap for K between J at index 4 and M at index 5.
Figure 13. Adding K: the splay brings up M, K's neighbor.

add splays for the new value first. When the value is not in the set, the splay leaves one of its neighbors at the root: the greatest key less than it, or the least key greater. Adding K to this tree leaves M at the root.

K at the root, ringed, with weight 12. Its left child is J (5) with everything less than K; its right child is M (6), which kept its right subtree and lost its left. In the array below, K's cell at index 5 is outlined in red, and M through V have moved up one, to 6 through 11.
Figure 14. K takes M's place, at index 5.

The new node takes the root's place. K is less than M, so K takes M's left subtree as its own, and M, with only its right subtree, becomes K's right child. The code touches M, then K, and K's index is the weight of its left subtree, 5. So the set tells its observers that it added K at index 5, and an array bound to the set splices K in at 5. The array has to move M and everything after it. The tree moved one subtree. Had the splay left the lesser neighbor at the root, the new node would take that neighbor as its left child instead, and the index would still be the weight of the new node's left subtree.

Listing 11. add, sorted-set.js lines 62 to 105, with lines left out

SortedSet.prototype.add = function (value) {
  var node = new this.Node(value);
  if (this.root) {
    this.splay(value);
    if (!this.contentEquals(value, this.root.value)) {
      var comparison = this.contentCompare(value, this.root.value);
      …
      if (comparison < 0) {
                // rotate right
                //   R        N
                //  / \  ->  / \
                // l   r    l   R
                // :   :    :    \
                //                r
                //                :
        node.right = this.root;
        node.left = this.root.left;
        this.root.left = null;
        this.root.touch();
      } else {
                // rotate left
                //   R        N
                //  / \  ->  / \
                // l   r    R   r
                // :   :   /    :
                //        l
                //        :
        node.left = this.root;
        node.right = this.root.right;
        this.root.right = null;
        this.root.touch();
      }
      node.touch();
      this.root = node;
      this.length++;
      if (this.dispatchesRangeChanges) {
        this.dispatchRangeChange([value], [], this.root.index);
      }
      return true;

Deleting #

Deleting N. The splay brings N, ringed, to the root with weight 12. Its left subtree, M with weight 7, holds B, D, F, H, J, K and M; its right subtree, P with weight 4, holds P, S, T and V. Below, the array of twelve keys, N's cell at index 7 outlined in red.
Figure 15. Deleting N: the splay brings N up, at index 7.

delete splays for the value too, and if the root holds it, its index is the weight of its left subtree. Deleting N: N is at index 7.

N is gone, marked by a dashed red circle. Its right subtree, P with weight 4, is set aside to the right. Its left subtree has been splayed for N again, and since every key in it is less than N, its greatest key, M, ringed, is at the root with weight 7 and no right child.
Figure 16. N's right subtree set aside, and its left splayed for N again.

To take N out, the code sets its right subtree aside and makes its left subtree the whole tree. Then it splays that tree for N again. Every key there is less than N, so the splay brings up the greatest of them, M, which can have no right child.

P's subtree hangs on M's empty right side, and M, ringed, is touched: weight 11. In the array below, N's cell is a dashed gap at index 7, and P, S, T and V have moved down one, to 7 through 10.
Figure 17. The right subtree hangs back on M, and N is gone from index 7.

The set-aside subtree hangs on M's empty right side, and the code touches M, which weighs 11. The set tells its observers that it removed N from index 7, the index it read before taking N out. If N had had no left subtree, its right subtree would simply have become the tree.

Listing 12. delete, sorted-set.js lines 121 to 153

SortedSet.prototype["delete"] = function (value) {
  if (this.root) {
    this.splay(value);
    if (this.contentEquals(value, this.root.value)) {
      var index = this.root.index;
      if (this.dispatchesRangeChanges) {
        this.dispatchRangeWillChange([], [value], index);
      }
      if (!this.root.left) {
        this.root = this.root.right;
      } else {
                // remove the right side of the tree,
        var right = this.root.right;
        this.root = this.root.left;
                // the tree now only contains the left side of the tree, so all
                // values are less than the value deleted.
                // splay so that the root has an empty right child
        this.splay(value);
                // put the right side of the tree back
        this.root.right = right;
      }
      this.length--;
      if (this.root) {
        this.root.touch();
      }
      if (this.dispatchesRangeChanges) {
        this.dispatchRangeChange([], [value], index);
      }
      return true;
    }
  }
  return false;
};

Finding by index #

The weights also run the other way. splayIndex walks down from the root, keeping a running index from the weights of the subtrees it steps past, until it reaches the node at the index it wants, then splays for that node's value. slice and splice start there, so a sorted set answers to array positions as well as to keys.

Listing 13. splayIndex, sorted-set.js lines 447 to 470

// an internal utility for splaying a node based on its index
SortedSet.prototype.splayIndex = function (index) {
  if (this.root) {
    var at = this.root;
    var atIndex = this.root.index;

    while (atIndex !== index) {
      if (atIndex > index && at.left) {
        at = at.left;
        atIndex -= 1 + (at.right ? at.right.length : 0);
      } else if (atIndex < index && at.right) {
        at = at.right;
        atIndex += 1 + (at.left ? at.left.length : 0);
      } else {
        break;
      }
    }

    this.splay(at.value);

    return this.root.index === index;
  }
  return false;
};

Verification #

The library's tests check every node's weight at the end of fifty random runs of adds, deletes and lookups, and bind a sorted set to an array through its range changes and compare them.

The figures are drawn from a line-for-line port of the library's splay, checked against the library, run on these keys, with every weight as the code stored it at each step, the stale ones included.

Since #

The splay tree has kept theorists busy. Sleator and Tarjan conjectured that it is dynamically optimal, within a constant factor of the best any binary search tree could do on every long enough sequence of accesses [1, p. 685], and that is still open; Iacono surveys the bounds proved on the way, the working set and dynamic finger among them [14]. Pettie bounds Tarjan's deque conjecture, about splay trees used as double-ended queues, by transcribing their rotations as Davenport–Schinzel sequences [15]. Sleator and Tarjan themselves gave variants that restructure less, such as semi-splaying [1, p. 670]. None of that changes for a weight. The roll-up costs one more pass over the path the splay already took, so whatever bound holds for the splay holds, within a constant, for the splay that watches its weight.

The code, whole #

Here are add, delete, indexOf, the whole splay with its history and roll-up, and touch, exactly as they are in the library at c785549.

Listing 14. add, delete and indexOf, sorted-set.js lines 62 to 163

SortedSet.prototype.add = function (value) {
  var node = new this.Node(value);
  if (this.root) {
    this.splay(value);
    if (!this.contentEquals(value, this.root.value)) {
      var comparison = this.contentCompare(value, this.root.value);
      if (comparison === 0) {
        throw new Error("SortedSet cannot contain incomparable but inequal values: " + value + " and " + this.root.value);
      }
      if (this.dispatchesRangeChanges) {
        this.dispatchRangeWillChange([value], [], this.root.index);
      }
      if (comparison < 0) {
                // rotate right
                //   R        N
                //  / \  ->  / \
                // l   r    l   R
                // :   :    :    \
                //                r
                //                :
        node.right = this.root;
        node.left = this.root.left;
        this.root.left = null;
        this.root.touch();
      } else {
                // rotate left
                //   R        N
                //  / \  ->  / \
                // l   r    R   r
                // :   :   /    :
                //        l
                //        :
        node.left = this.root;
        node.right = this.root.right;
        this.root.right = null;
        this.root.touch();
      }
      node.touch();
      this.root = node;
      this.length++;
      if (this.dispatchesRangeChanges) {
        this.dispatchRangeChange([value], [], this.root.index);
      }
      return true;
    }
  } else {
    if (this.dispatchesRangeChanges) {
      this.dispatchRangeWillChange([value], [], 0);
    }
    this.root = node;
    this.length++;
    if (this.dispatchesRangeChanges) {
      this.dispatchRangeChange([value], [], 0);
    }
    return true;
  }
  return false;
};

SortedSet.prototype["delete"] = function (value) {
  if (this.root) {
    this.splay(value);
    if (this.contentEquals(value, this.root.value)) {
      var index = this.root.index;
      if (this.dispatchesRangeChanges) {
        this.dispatchRangeWillChange([], [value], index);
      }
      if (!this.root.left) {
        this.root = this.root.right;
      } else {
                // remove the right side of the tree,
        var right = this.root.right;
        this.root = this.root.left;
                // the tree now only contains the left side of the tree, so all
                // values are less than the value deleted.
                // splay so that the root has an empty right child
        this.splay(value);
                // put the right side of the tree back
        this.root.right = right;
      }
      this.length--;
      if (this.root) {
        this.root.touch();
      }
      if (this.dispatchesRangeChanges) {
        this.dispatchRangeChange([], [value], index);
      }
      return true;
    }
  }
  return false;
};

SortedSet.prototype.indexOf = function (value) {
  if (this.root) {
    this.splay(value);
    if (this.contentEquals(value, this.root.value)) {
      return this.root.index;
    }
  }
  return -1;
};

Listing 15. splay, sorted-set.js lines 325 to 445

// This is the simplified top-down splaying algorithm from: "Self-adjusting
// Binary Search Trees" by Sleator and Tarjan. Guarantees that root.value
// equals value if value exists. If value does not exist, then root will be
// the node whose value either immediately preceeds or immediately follows value.
// - as described in https://github.com/hij1nx/forest
SortedSet.prototype.splay = function (value) {
  var stub, left, right, temp, root, history;

  if (!this.root) {
    return;
  }

    // Create a stub node.  The use of the stub node is a bit
    // counter-intuitive: The right child of the stub node will hold the L tree
    // of the algorithm.  The left child of the stub node will hold the R tree
    // of the algorithm.  Using a stub node, left and right will always be
    // nodes and we avoid special cases.
    // - http://code.google.com/p/v8/source/browse/branches/bleeding_edge/src/splay-tree-inl.h
  stub = left = right = new this.Node();
    // The history is an upside down tree used to propagate new tree sizes back
    // up the left and right arms of a traversal.  The right children of the
    // transitive left side of the tree will be former roots while linking
    // left.  The left children of the transitive walk to the right side of the
    // history tree will all be previous roots from linking right.  The last
    // node of the left and right traversal will each become a child of the new
    // root.
  history = new this.Node();
  root = this.root;

  for (;;) {
    var comparison = this.contentCompare(value, root.value);
    if (comparison < 0) {
      if (root.left) {
        if (this.contentCompare(value, root.left.value) < 0) {
                    // rotate right
                    //        Root         L(temp)
                    //      /     \       / \
                    //     L(temp) R    LL    Root
                    //    / \                /    \
                    //  LL   LR            LR      R
          temp = root.left;
          root.left = temp.right;
          root.touch();
          temp.right = root;
          temp.touch();
          root = temp;
          if (!root.left) {
            break;
          }
        }
                // remember former root for repropagating length
        temp = new Node();
        temp.right = root;
        temp.left = history.left;
        history.left = temp;
                // link left
        right.left = root;
        right.touch();
        right = root;
        root = root.left;
      } else {
        break;
      }
    } else if (comparison > 0) {
      if (root.right) {
        if (this.contentCompare(value, root.right.value) > 0) {
                    // rotate left
                    //        Root         L(temp)
                    //      /     \       / \
                    //     L(temp) R    LL    Root
                    //    / \                /    \
                    //  LL   LR            LR      R
          temp = root.right;
          root.right = temp.left;
          root.touch();
          temp.left = root;
          temp.touch();
          root = temp;
          if (!root.right) {
            break;
          }
        }
                // remember former root for repropagating length
        temp = new Node();
        temp.left = root;
        temp.right = history.right;
        history.right = temp;
                // link right
        left.right = root;
        left.touch();
        left = root;
        root = root.right;
      } else {
        break;
      }
    } else { // equal or incomparable
      break;
    }
  }

    // reassemble
  left.right = root.left;
  left.touch();
  right.left = root.right;
  right.touch();
  root.left = stub.right;
  root.right = stub.left;

    // propagate new lengths
  while (history.left) {
    history.left.right.touch();
    history.left = history.left.left;
  }
  while (history.right) {
    history.right.left.touch();
    history.right = history.right.right;
  }
  root.touch();

  this.root = root;
};

Listing 16. touch, sorted-set.js lines 599 to 604

Node.prototype.touch = function () {
  this.length = 1 +
        (this.left ? this.left.length : 0) +
        (this.right ? this.right.length : 0);
  this.index = this.left ? this.left.length : 0;
};

References #

  1. Daniel Dominic Sleator and Robert Endre Tarjan. “Self-Adjusting Binary Search Trees.” Journal of the ACM 32, no. 3 (July 1985): 652–686. doi:10.1145/3828.3835. Read in the scan on Daniel Sleator’s page.
  2. Kris Kowal. “Implement index tracking in SortedSet.” Commit to collections, October 27, 2012. github.com/kriskowal/collections/commit/471ec59.
  3. Kris Kowal. @collections/sorted-set, sorted-set.js, at commit c785549, October 2, 2020. github.com/kriskowal/collections/blob/c785549/packages/sorted-set/sorted-set.js.
  4. Kris Kowal. “FIRST!” First commit to collections, splay-set.js, July 27, 2012. github.com/kriskowal/collections/blob/8a876b7/splay-set.js.
  5. Fedor Indutny. callgrind.js, lib/callgrind/splaytree.js, initial commit, July 12, 2012. github.com/indutny/callgrind.js/blob/6682d7b/lib/callgrind/splaytree.js.
  6. Kris Kowal. “Reimplemented splay set without parent nodes.” Commit to collections, July 27, 2012. github.com/kriskowal/collections/commit/19bcbdf.
  7. Paolo Fragomeni. forest, lib/splayTree.js, “adapted from the V8 project,” December 19, 2011. github.com/hij1nx/forest/blob/64e6fa2/lib/splayTree.js.
  8. The V8 project authors. V8, tools/splaytree.js, the tick processor’s splay tree, at commit 5c57d0d, July 13, 2011. github.com/v8/v8/blob/5c57d0d/tools/splaytree.js.
  9. Kris Kowal. collections, README.md, “References,” July 27, 2012. github.com/kriskowal/collections/blob/aed15d9/README.md.
  10. Yoichi Hirai and Kazuhiko Yamamoto. “Balancing Weight-Balanced Trees.” Journal of Functional Programming 21, no. 3 (2011): 287–307. doi:10.1017/S0956796811000104.
  11. The Haskell containers authors. containers, Data/Map/Internal.hs, findIndex, lookupIndex and elemAt, at commit 953428a. github.com/haskell/containers/blob/953428a/containers/src/Data/Map/Internal.hs.
  12. Leo J. Guibas and Robert Sedgewick. “A Dichromatic Framework for Balanced Trees.” In 19th Annual Symposium on Foundations of Computer Science, 8–21. IEEE, 1978. doi:10.1109/SFCS.1978.3.
  13. The V8 project authors. V8, src/splay-tree-inl.h, SplayTree::Splay, at commit 6125718, June 11, 2012. github.com/v8/v8/blob/6125718/src/splay-tree-inl.h.
  14. John Iacono. “In Pursuit of the Dynamic Optimality Conjecture.” In Space-Efficient Data Structures, Streams, and Algorithms, Lecture Notes in Computer Science 8066, 236–250. Springer, 2013. doi:10.1007/978-3-642-40273-9_16; arXiv:1306.0207.
  15. Seth Pettie. “Splay Trees, Davenport-Schinzel Sequences, and the Deque Conjecture.” Preprint, July 2007. arXiv:0707.2160.
Basic Binary Board Book
Now on Amazon!