Simple Algorithm
Algorithms & Data Structures · Optimal · 24 min

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 nn frames. Yet a binary tree with nn nodes contains n+1n+1 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 O(n)O(n) time with O(1)O(1) 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 n+1n+1 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 4n−34n-3 pointers.
  • Explain Schorr–Waite pointer reversal, which marks any graph with two pointers per node using one tag bit per node and O(1)O(1) 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 nn nodes has 2n2n child pointers, and only n−1n-1 of them lead to nodes, so n+1n+1 are empty. A recursive or stack-based traversal ignores them and spends O(h)O(h) extra words remembering the way back up, up to nn on a path. Perlis and Thornton (1960) put the empty pointers to work.

With right threads alone, inorder needs no stack. The successor of xx is either one thread away, or, when xx has a real right child, the leftmost node of its right subtree:

python
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 out

Each real edge is followed once, downward, and each thread once, upward: fewer than 2n2n pointer moves and O(1)O(1) 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 xx with a left subtree, it finds xx's inorder predecessor pp, the rightmost node of the left subtree. Being rightmost, pp has an empty right pointer, and it is the last node the walk of the left subtree will visit. So the algorithm points p.rightp.\text{right} back at xx and descends: when the left subtree is done, the walk follows the thread back to xx.

On that second arrival, the predecessor search ends at a pointer that already leads to xx. That is the signal that the left subtree is finished: remove the thread, visit xx, and go right.

python
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 out

For preorder, visit xx when the thread is created instead of when it is removed (and, as before, when xx 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.

Check your understanding

Morris inorder runs on the BST built by inserting 8, 3, 10, 1, 6, 14, 4, 7, 13. Which thread does it create first?

  1. From 1 back to 3
  2. From 7 back to 8
  3. From 13 back to 14
  4. 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 {3,1,6,4,7}\{3,1,6,4,7\}. 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.

text
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 14

The 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

DerivationProof
  1. left subtree of x ⟶ x ⟶ right subtree of x\text{left subtree of }x\ \longrightarrow\ x\ \longrightarrow\ \text{right subtree of }x

    Correctness. At a node xx with a left subtree, the thread makes the walk of that subtree end at xx, exactly where a recursive traversal would return. Finding p.right=xp.\text{right}=x on the second arrival shows that the left subtree is done, so xx 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.

  2. main moves=n+L\text{main moves}=n+L

    The main walk. After each of the nn visits, xx follows one pointer (a right child, a thread, or the final empty pointer), and each of the LL nodes with a left child sends xx down one extra time:

  3. search moves=2∑x(1+sx)=2(L+S)\text{search moves}=2\sum_{x}\big(1+s_x\big)=2(L+S)

    The searches. A node xx with a left child searches for its predecessor twice, each time following x.leftx.\text{left} and then the sxs_x right edges of the right spine below it:

  4. L+S ≤ n−1⟹n+3L+2S ≤ n+3(L+S) ≤ 4n−3L+S\ \le\ n-1\quad\Longrightarrow\quad n+3L+2S\ \le\ n+3(L+S)\ \le\ 4n-3

    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 LL left edges and the SS spine edges are therefore distinct edges of the tree:

  5. L=n−1, S=0:n+3(n−1)=4n−3L=n-1,\ S=0:\qquad n+3(n-1)=4n-3

    The bound is tight. A left path, in which every node is the left child of the previous one, has L=n−1L=n-1 and S=0S=0; a right path has L=0L=0 and costs only nn. An exhaustive check over all shapes with up to 9 nodes confirms that 4n−34n-3 is the maximum.

Predict before you look

Morris inorder runs on a left path of 100 nodes. How many pointers does it follow in total?

Show the answer

397 pointer moves

L=99L=99 and S=0S=0, so n+3L=100+297=397=4n−3n+3L=100+297=397=4n-3, 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 2L=1982L=198 writes, for its O(1)O(1) 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.

python
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 up

Python 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.

MethodExtra space while walkingWrites to the treeTime
Recursion or an explicit stackO(h)O(h) words, up to nnnoneΘ(n)\Theta(n)
Parent pointersO(1)O(1) words, but nn extra pointers storednone during the walkΘ(n)\Theta(n)
Threaded treeO(1)O(1) words, but 2 tag bits per node storednone during the walk; updates must maintain the threadsΘ(n)\Theta(n)
Morris traversalO(1)O(1) words2L2L temporary writesΘ(n)\Theta(n), at most 4n−34n-3 pointer moves
Schorr–Waite markingO(1)O(1) words, plus a tag bit per nodetemporary reversed pointersΘ(N)\Theta(N) for NN reachable nodes
Successor search from the root (BST only)O(1)O(1) wordsnoneO(nh)O(nh)
Every row is a different answer to one question: where is the way back up stored? In a stack, in the nodes for good, in the nodes for a while, or nowhere, at the price of searching for it again.

Key takeaways

  • A binary tree with nn nodes has n+1n+1 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 xx's left subtree back to xx, and removes it on the second arrival: O(1)O(1) extra words, the tree restored, and exactly n+3L+2S≤4n−3n+3L+2S\le4n-3 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.
  • O(1)O(1) 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 O(nh)O(nh) time.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

At a node xx with a left child, Morris traversal threads xx's inorder predecessor back to xx. Where is that predecessor, and why is its right pointer free?

  1. It is xx's parent, whose right pointer is free when xx is a left child
  2. It is the leftmost node of xx's right subtree, which has no left child
  3. It is the rightmost node of xx's left subtree, which by definition has no right child
  4. It is any leaf of xx's left subtree, since leaves have two empty pointers
Show the answer

C. It is the rightmost node of xx's left subtree, which by definition has no right child

The predecessor of xx is the largest node before it in inorder, the end of the right spine of xx'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 xx at exactly the right moment.

Question 2

Every node with a left child makes Morris traversal walk to its predecessor twice. Why is the total still O(n)O(n)?

  1. Each walk is short: at most log⁡2n\log_2 n steps in any tree
  2. The walks follow the right spines of left subtrees, which share no edges, so together they follow each edge at most twice
  3. It is O(n)O(n) only on balanced trees
  4. 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 2L2L walks together take 2(L+S)≤2(n−1)2(L+S)\le2(n-1) steps. With the main walk's n+Ln+L moves, the total is at most 4n−34n-3.

Question 3

What does the Schorr–Waite algorithm keep in each node's tag bit?

  1. Whether the node is reachable from the root
  2. Whether the node's right pointer is a thread
  3. The node's depth, modulo 2
  4. 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.

Question 4

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 O(1)O(1) extra words. What works?

  1. Search from the root for the successor of the last key listed, again and again: O(nh)O(nh) time
  2. Morris traversal: O(n)O(n) time
  3. An explicit stack: O(n)O(n) time
  4. 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: O(nh)O(nh) time

The keys themselves show the way: the successor of kk is found by one downward walk from the root (the last node where the walk turned left), in O(h)O(h) time with O(1)O(1) words and no writes. nn such walks cost O(nh)O(nh): O(nlog⁡n)O(n\log n) on a balanced tree, Θ(n2)\Theta(n^2) 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).