workshop private

← all creations

Thread

viz · created 2026-09-13

Morris in-order traversal beside the stack version on the same tree — the O(1)-space walk doesn't delete the stack, it writes it into the tree's unused right pointers, and for the length of the walk the tree is not a tree.

algorithmsinterview-prepcanvas

Two in-order traversals of one binary search tree, stepping together. On the left, the iterative version everyone writes: push down the left spine, pop to visit, step right, with the stack drawn as a column of cells beside the tree. On the right, Morris traversal — the one whose selling point is O(1) auxiliary space — with an identical column that stays empty the whole way.

The empty column is the setup. The payoff is what’s happening in the tree next to it. Before Morris descends into a left subtree it finds that subtree’s rightmost node — the current node’s in-order predecessor — and points that node’s unused right at the current node. That borrowed pointer is a thread, drawn here as a dashed arc curving back up, and it is the only reason the walk can find its way home. Come back to a node whose predecessor already threads to it and the left subtree is finished: cut the thread, put the pointer back exactly as it was, visit the node, step right.

So watch the two columns and then watch the strip under them, where cells held per step is drawn back to back at one scale — stack depth growing up, live threads growing down. The two silhouettes are the same shape, off by one. The stack did not disappear. It moved. Both walks have to remember the same chain of ancestors they still owe a visit to; the left one keeps that chain in memory it asked for, and Morris keeps it in pointer slots that happened to be lying around inside the data structure. On a left chain tree, stack depth 9 sits opposite 8 live threads drawn as eight parallel arcs you can count. On a right chain there is nothing to come back to, so the stack never exceeds 1 and Morris never threads at all — it is free, and exactly as free as the other one.

Two things that cost real money, both on screen:

And at the end, the thing worth proving rather than asserting: the two trees are drawn identically and the tree’s fingerprint — every node, every link — is compared against the one taken before the walk started. Restored exactly, 14 pointer writes later.

Reuse

src/thread.js is a framework-free ES module:

traceMorris works on its own copy of the nodes, so calling it does not mutate the tree you passed in. No rendering or timers in the module; the canvas demo is reference code.

Gotchas