Tree Traversal in O(1) Space
Threaded trees, Morris traversal and pointer reversal.
Every recursive traversal hides a stack as deep as the tree, up to frames. Yet a binary tree with nodes contains pointers that point nowhere, and they are enough to remember the way back. Threaded trees keep links to inorder neighbors there for good; Morris traversal threads and unthreads them on the fly, walking any binary tree in time with extra words; and Schorr–Waite pointer reversal marks whole memory graphs the same way, in garbage collectors that run exactly when memory has run out.
What you’ll learn
- Use the empty pointers of a binary tree to build a threaded tree, and walk it in inorder without a stack.
- Implement Morris inorder and preorder traversal, and prove that it restores the tree and follows at most pointers.
- Explain Schorr–Waite pointer reversal, which marks any graph with two pointers per node using one tag bit per node and extra words.
- Compare stacks, parent pointers, threads, Morris traversal and read-only walks by extra space, writes and time.
The n + 1 empty pointers: threaded trees
A binary tree with nodes has child pointers, and only of them lead to nodes, so are empty. A recursive or stack-based traversal ignores them and spends extra words remembering the way back up, up to on a path. Perlis and Thornton (1960) put the empty pointers to work.
With right threads alone, inorder needs no stack. The successor of is either one thread away, or, when has a real right child, the leftmost node of its right subtree:
def threaded_inorder(root): # x.rthread: x.right is a thread
out, x = [], root
while x is not None and x.left is not None:
x = x.left # start at the leftmost node
while x is not None:
out.append(x.key)
if x.rthread:
x = x.right # a thread leads straight to the successor
else:
x = x.right # a real right child: go right once,
while x.left is not None:
x = x.left # then left as far as possible
return outEach real edge is followed once, downward, and each thread once, upward: fewer than pointer moves and extra words. Checked against recursive inorder on 2,000 random trees.
Morris traversal: threads on the fly
Morris traversal (Morris, 1979) needs no tag bits and leaves no threads behind. At a node with a left subtree, it finds 's inorder predecessor , the rightmost node of the left subtree. Being rightmost, has an empty right pointer, and it is the last node the walk of the left subtree will visit. So the algorithm points back at and descends: when the left subtree is done, the walk follows the thread back to .
On that second arrival, the predecessor search ends at a pointer that already leads to . That is the signal that the left subtree is finished: remove the thread, visit , and go right.
def morris_inorder(root):
out, x = [], root
while x is not None:
if x.left is None:
out.append(x.key) # no left subtree: visit, then go right
x = x.right
else:
p = x.left # x's inorder predecessor: the
while p.right is not None and p.right is not x:
p = p.right # rightmost node of the left subtree
if p.right is None: # first arrival: thread p back to x,
p.right = x # then walk the left subtree
x = x.left
else: # second arrival, through the thread:
p.right = None # remove it, restoring the tree,
out.append(x.key) # and visit x
x = x.right
return outFor preorder, visit when the thread is created instead of when it is removed (and, as before, when has no left child). Both versions were checked on 5,000 random trees: the output is correct and the tree afterwards is identical to the tree before.
Morris inorder runs on the BST built by inserting 8, 3, 10, 1, 6, 14, 4, 7, 13. Which thread does it create first?
- From 1 back to 3
- From 7 back to 8
- From 13 back to 14
- From 4 back to 6
Show the answer
B. From 7 back to 8
The walk starts at the root, 8, which has a left subtree . Its predecessor is that subtree's rightmost node: from 3 go right to 6, then right to 7, which has no right child. So the first thread runs from 7 back to 8; the threads 1 → 3, 4 → 6 and 13 → 14 come later.
x = 8 left subtree {3, 1, 6, 4, 7}: thread 7 → 8, go left
x = 3 thread 1 → 3, go left
x = 1 no left child: visit 1, follow the thread to 3
x = 3 second arrival: remove 1 → 3, visit 3, go right
x = 6 thread 4 → 6, go left
x = 4 visit 4, follow the thread to 6
x = 6 remove 4 → 6, visit 6, go right
x = 7 visit 7, follow the thread to 8
x = 8 remove 7 → 8, visit 8, go right
x = 10 visit 10, go right
x = 14 thread 13 → 14, go left
x = 13 visit 13, follow the thread to 14
x = 14 remove 13 → 14, visit 14, go right: x = None, done
output 1 3 4 6 7 8 10 13 14The full trace. Every thread is created once and removed once, and at the end the tree is exactly as it was.
Why it runs in linear time
Correctness. At a node with a left subtree, the thread makes the walk of that subtree end at , exactly where a recursive traversal would return. Finding on the second arrival shows that the left subtree is done, so is visited after its left subtree and before its right one; by induction on subtrees the output is the inorder, and every thread is removed right after its single use.
The main walk. After each of the visits, follows one pointer (a right child, a thread, or the final empty pointer), and each of the nodes with a left child sends down one extra time:
The searches. A node with a left child searches for its predecessor twice, each time following and then the right edges of the right spine below it:
The spines are disjoint. Climb from a right edge along right edges as far as possible: the top is unique, and it is the left child of at most one node, so each right edge lies on at most one spine. The left edges and the spine edges are therefore distinct edges of the tree:
The bound is tight. A left path, in which every node is the left child of the previous one, has and ; a right path has and costs only . An exhaustive check over all shapes with up to 9 nodes confirms that is the maximum.
Morris inorder runs on a left path of 100 nodes. How many pointers does it follow in total?
Show the answer
397 pointer moves
and , so , the worst case. Each node's predecessor is its own left child: one step to create the thread, one to remove it, plus the main walk's step down and its return through the thread. A stack-based walk follows each of the 99 edges once, downward, so Morris pays about four times as many pointer moves, plus writes, for its space.
Pointer reversal, and the price of O(1) space
A garbage collector must mark every object reachable from the program's roots, and it runs exactly when memory is scarce, so an unbounded mark stack is a liability. Schorr and Waite (1967), and independently Deutsch, marked with no stack at all. On the way down, the pointer just followed is reversed to point back to the parent, so the path to the root is stored in the nodes themselves; on the way back up each pointer is restored. One tag bit per node records which of its two fields currently holds the reversed link.
def schorr_waite_mark(root): # nodes: mark, tag, left, right
prev, cur = None, root
while True:
while cur is not None and not cur.mark: # descend leftward through new nodes
cur.mark, cur.tag = True, 0
cur.left, prev, cur = prev, cur, cur.left # left now points back up
while prev is not None and prev.tag == 1: # right side done: restore it, climb
back = prev.right
prev.right, cur, prev = cur, prev, back
if prev is None:
return # climbed above the root: done
back = prev.left # left side done: restore left,
prev.left, prev.tag = cur, 1 # then explore the right side,
cur, prev.right = prev.right, back # whose field now points back upPython evaluates the right side of a tuple assignment first, so each rotation of three pointers is one line. It works on any graph with two pointer fields per node, cycles and shared nodes included: on 3,000 random graphs it marked exactly the reachable nodes and restored every pointer.
| Method | Extra space while walking | Writes to the tree | Time |
|---|---|---|---|
| Recursion or an explicit stack | words, up to | none | |
| Parent pointers | words, but extra pointers stored | none during the walk | |
| Threaded tree | words, but 2 tag bits per node stored | none during the walk; updates must maintain the threads | |
| Morris traversal | words | temporary writes | , at most pointer moves |
| Schorr–Waite marking | words, plus a tag bit per node | temporary reversed pointers | for reachable nodes |
| Successor search from the root (BST only) | words | none |
Key takeaways
- A binary tree with nodes has empty pointers. Threaded trees (Perlis & Thornton, 1960) fill them with links to inorder neighbors, so inorder needs no stack, at the price of a tag bit per pointer.
- Morris traversal (1979) creates each thread temporarily, from the rightmost node of 's left subtree back to , and removes it on the second arrival: extra words, the tree restored, and exactly pointer moves, because the predecessor walks follow disjoint spines.
- Schorr–Waite pointer reversal stores the way back in the pointers themselves, marking any two-pointer graph in linear time with one tag bit per node: the classic stackless marker of garbage collectors.
- space is paid for with writes: these methods are unsafe for concurrent readers and impossible on read-only trees, where a BST can still be walked by successor searches from the root in time.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
At a node with a left child, Morris traversal threads 's inorder predecessor back to . Where is that predecessor, and why is its right pointer free?
- It is 's parent, whose right pointer is free when is a left child
- It is the leftmost node of 's right subtree, which has no left child
- It is the rightmost node of 's left subtree, which by definition has no right child
- It is any leaf of 's left subtree, since leaves have two empty pointers
Show the answer
C. It is the rightmost node of 's left subtree, which by definition has no right child
The predecessor of is the largest node before it in inorder, the end of the right spine of 's left subtree. It is rightmost, so its right pointer is empty, and it is the last node the walk of the left subtree visits: a thread there returns the walk to at exactly the right moment.
Every node with a left child makes Morris traversal walk to its predecessor twice. Why is the total still ?
- Each walk is short: at most steps in any tree
- The walks follow the right spines of left subtrees, which share no edges, so together they follow each edge at most twice
- It is only on balanced trees
- A tag bit lets the second walk be skipped
Show the answer
B. The walks follow the right spines of left subtrees, which share no edges, so together they follow each edge at most twice
Each right edge lies on the right spine of at most one left subtree, and each left edge starts exactly one spine walk, so the walks together take steps. With the main walk's moves, the total is at most .
What does the Schorr–Waite algorithm keep in each node's tag bit?
- Whether the node is reachable from the root
- Whether the node's right pointer is a thread
- The node's depth, modulo 2
- Which of the node's two fields currently holds the reversed link to its parent
Show the answer
D. Which of the node's two fields currently holds the reversed link to its parent
The reversed fields store the way back to the root. When the walk returns to a node, it must know whether it is coming back from the left side (then restore the left field and move the reversed link into the right one) or from the right side (then restore the right field and climb). The tag records exactly that.
You must list a large BST's keys in sorted order. The tree is read-only, has no parent pointers, and you may use only extra words. What works?
- Search from the root for the successor of the last key listed, again and again: time
- Morris traversal: time
- An explicit stack: time
- Nothing: without a stack or writes it cannot be done
Show the answer
A. Search from the root for the successor of the last key listed, again and again: time
The keys themselves show the way: the successor of is found by one downward walk from the root (the last node where the walk turned left), in time with words and no writes. such walks cost : on a balanced tree, on a path. That is the price of storing the way back nowhere.
Further reading
- J. M. Morris, "Traversing binary trees simply and cheaply," Information Processing Letters (1979).
- A. J. Perlis & C. Thornton, "Symbol manipulation by threaded lists," Communications of the ACM (1960).
- H. Schorr & W. M. Waite, "An efficient machine-independent procedure for garbage collection in various list structures," Communications of the ACM (1967).
- D. E. Knuth, The Art of Computer Programming, vol. 1: Fundamental Algorithms, 3rd ed. (Addison-Wesley, 1997), sections 2.3.1 and 2.3.5.
- O. Reingold, "Undirected connectivity in log-space," Journal of the ACM (2008).