Weight Watching Splay Trees

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;
};

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;

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.

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;
}
}

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;

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 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 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 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 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 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;
}

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;
}

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 #

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.

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 #

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.

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.

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 #
- 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.
- Kris Kowal. “Implement index tracking in SortedSet.” Commit to collections, October 27, 2012. github.com/kriskowal/collections/commit/471ec59.
- 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. - Kris Kowal. “FIRST!” First commit to collections,
splay-set.js, July 27, 2012. github.com/kriskowal/collections/blob/8a876b7/splay-set.js. - Fedor Indutny. callgrind.js,
lib/callgrind/splaytree.js, initial commit, July 12, 2012. github.com/indutny/callgrind.js/blob/6682d7b/lib/callgrind/splaytree.js. - Kris Kowal. “Reimplemented splay set without parent nodes.” Commit to collections, July 27, 2012. github.com/kriskowal/collections/commit/19bcbdf.
- Paolo Fragomeni. forest,
lib/splayTree.js, “adapted from the V8 project,” December 19, 2011. github.com/hij1nx/forest/blob/64e6fa2/lib/splayTree.js. - 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. - Kris Kowal. collections,
README.md, “References,” July 27, 2012. github.com/kriskowal/collections/blob/aed15d9/README.md. - Yoichi Hirai and Kazuhiko Yamamoto. “Balancing Weight-Balanced Trees.” Journal of Functional Programming 21, no. 3 (2011): 287–307. doi:10.1017/S0956796811000104.
- The Haskell containers authors. containers,
Data/Map/Internal.hs,findIndex,lookupIndexandelemAt, at commit 953428a. github.com/haskell/containers/blob/953428a/containers/src/Data/Map/Internal.hs. - 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.
- 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. - 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.
- Seth Pettie. “Splay Trees, Davenport-Schinzel Sequences, and the Deque Conjecture.” Preprint, July 2007. arXiv:0707.2160.
















