Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Trees

Threading the Tree.

Watch the explainer

Inorder traversal normally needs a stack (or recursion’s call stack) — O(h) extra space — to remember how to get back up after visiting a left subtree. Morris traversal removes that cost entirely by borrowing the tree itself: before descending left, it wires the subtree’s rightmost node (the inorder predecessor) with a temporary thread pointing back to the current node. When the traversal returns along that thread, it knows to visit and then undo the thread, leaving the tree exactly as it found it. Step through and watch the threads flicker in and out.

O(n) time · O(1) extra space · no stack, no recursion, tree restored
inorder

Left subtree, node, right subtree — for a BST this yields sorted order.

predecessor

The rightmost node of a node’s left subtree — the value visited just before it.

thread

A temporary right pointer from a predecessor back to its node, used to climb back up.

restore

On the second visit to a node, the thread is removed — the tree ends unchanged.

morris.js — borrow a pointer, then give it back
Ready
A binary search tree. We inorder-traverse it with no stack: before going left, thread the left subtree’s rightmost node back to here; follow that thread later to climb back. Step through the loop.
4
at node
0
live threads
O(1)
extra space
output:

How it works

The single idea is that a leaf’s unused right pointer is free storage. A node’s inorder predecessor is the rightmost node of its left subtree, and that node’s right pointer is null — nowhere to go. Morris borrows it: point it back at the current node so that when the left subtree finishes, following that right pointer lands exactly where the traversal needs to resume. Seeing the thread already in place on a second visit is the signal to undo it and move right.

1

No left child? Visit and go right

If the current node has no left subtree, there’s nothing to defer — visit it (emit its value) and move to its right pointer.

2

Has a left child? Find the predecessor

Walk to the rightmost node of the left subtree. That node is the inorder predecessor of the current node.

3

First visit: thread and go left

If the predecessor’s right is null, set it to point back to the current node (create the thread) and descend into the left subtree.

✓

Second visit: unthread, visit, go right

If the predecessor’s right already points back here, the left subtree is done. Remove the thread (restore the tree), visit the current node, and move right. Every thread created is undone.

Time
O(n)
Extra space
O(1)
Stack / recursion
None
Tree after
Unchanged

The code

# inorder traversal, O(1) extra space, tree restored def morris_inorder(root): cur, out = root, [] while cur: if not cur.left: out.append(cur.val); cur = cur.right # visit, go right else: pre = cur.left while pre.right and pre.right is not cur: pre = pre.right # rightmost = predecessor if pre.right is None: pre.right = cur; cur = cur.left # thread, descend left else: pre.right = None # unthread (restore) out.append(cur.val); cur = cur.right # visit, go right return out

Quick check

1. What extra space does Morris traversal use?

2. When a node has a left child, what does Morris do first?

3. What is the state of the tree after Morris traversal finishes?

FAQ

What is Morris traversal?

An algorithm that traverses a binary tree inorder using O(1) extra space — no stack, no recursion. It temporarily threads each inorder predecessor’s right pointer back to its node, uses those threads to climb back up, and removes each one so the tree ends unchanged.

How does Morris traversal avoid using a stack?

Normal inorder needs a stack to remember how to return after a left subtree. Morris stores that return path in the tree itself — pointing the left subtree’s rightmost node (whose right pointer is unused) back at the current node. Following it later returns to the right place, so no stack is needed.

What is the downside of Morris traversal?

It temporarily mutates the tree (adding threads), so it’s not safe under concurrent reads or on an immutable tree, and it’s trickier to get right than a stack-based traversal. Some nodes are visited twice (thread, then unthread), though total work stays O(n).

When would you use Morris traversal?

When you need strict O(1) extra space — very deep trees where an O(h) stack is too costly, or memory-constrained environments. In everyday code a recursive or stack-based traversal is clearer and usually preferred.

The picture: borrowed pointers

426 1357 thread 3 → 4 thread 1 → 2 thread 5 → 6 highlighted: the rightmost node of each left subtree, whose empty right pointer is borrowed
The seven-node tree traced below. Every node that has a left child (4, 2 and 6) gets one temporary thread, written into the empty right pointer of the rightmost node of its left subtree (3, 1 and 5). The threads are never all present at once: the trace shows at most 2 alive together, and all are removed again before the traversal ends.

Worked example, step by step

Take the binary search tree with root 4, children 2 and 6, and leaves 1, 3, 5, 7. Each row is one pass through the loop. “Threads alive” counts temporary pointers currently written into the tree, and “Output so far” is the inorder list.

#curCaseActionThreads aliveOutput so far
14left child, thread absentpredecessor 3: set 3.right = 4, go left1—
22left child, thread absentpredecessor 1: set 1.right = 2, go left2—
31no left childvisit 1, go right21
42thread presentremove 1.right, visit 2, go right11 2
53no left childvisit 3, go right11 2 3
64thread presentremove 3.right, visit 4, go right01 2 3 4
76left child, thread absentpredecessor 5: set 5.right = 6, go left11 2 3 4
85no left childvisit 5, go right11 2 3 4 5
96thread presentremove 5.right, visit 6, go right01 2 3 4 5 6
107no left childvisit 7, go right01 2 3 4 5 6 7

Read the highlighted rows: each is the second arrival at a node, found because its predecessor’s right pointer already leads back. That is the only signal Morris has that the left subtree is finished, and it is why the thread must be removed at that moment, not later. The output is 1, 2, 3, 4, 5, 6, 7, sorted as an inorder walk of a search tree should be, and the threads alive column ends at 0, so the tree is exactly as it started. Counting each loop pass plus each hop while hunting for a predecessor, this seven-node tree took 12 steps.

Complexity and trade-offs

CaseTimeSpaceWhy
Morris traversalO(n)O(1)Each edge on a left subtree’s right spine is walked at most twice (once to thread, once to unthread). Counted steps: 12 for 7 nodes, 2538 for a balanced 1,023-node tree, 1999 for a 1,000-node left-leaning chain.
Recursive inorderO(n)O(h)The call stack is as deep as the tree. Deepest stack: 10 frames for the balanced 1,023-node tree, 1,000 for the chain.
Iterative inorder with a stackO(n)O(h)The same depth, held in an explicit stack. It never touches the tree, so it is safe to use while other readers share it.
Parent pointers or a visited setO(n)O(n)Stores extra data for every node. Simple and mutation-free, but it costs the most memory.

Morris is not faster than a stack; it does about two to three pointer steps per node where a stack does one push and one pop. What it buys is memory: on a degenerate tree a stack grows to the number of nodes, while Morris stays at a handful of variables. The cost is that it temporarily writes to the tree, so it is wrong for a tree that other threads read at the same time, for read-only memory, and for any code that cannot tolerate a half-threaded tree if it stops early.

Common mistakes

  • Hunting for the predecessor without the “is not cur” check

    The inner loop must be while pre.right and pre.right is not cur. Without the second test, when a thread already exists the loop follows it back to cur and onward around the cycle. On the seven-node tree above, a version without the check never terminates; a run capped at 1,000 steps was still looping.

  • Forgetting to remove the thread

    If the second-visit branch does not set pre.right = None, the first traversal can still print 1, 2, 3, 4, 5, 6, 7, so a single test passes. But the tree is now corrupted: node 3 points up at node 4, and an ordinary recursive inorder walk of it keeps recursing until it overflows the stack or exceeds a depth guard.

  • Visiting at the wrong moment for preorder

    Inorder visits on the second arrival at a node. Preorder, using the same machinery, visits on the first, when the thread is created. Swapping the two lines gives 4, 2, 1, 3, 6, 5, 7 from the same tree. Mixing them up gives an inorder list that is not sorted.

  • Using it on a tree that is shared

    Another thread walking the tree while Morris has threads in place can follow a thread upward and see a cycle. Use a stack, or take a lock, whenever there are concurrent readers.

  • Assuming “O(1) space” means no stack at all in the output

    Only the auxiliary space is constant. The list of visited values is still O(n) if you collect it. Printing or yielding values as you go keeps the whole thing constant.

Where this shows up

  • Memory-tight tree walks

    Embedded or kernel-style code that cannot afford a recursion stack proportional to tree height can use the same idea. A long left-leaning chain needs a stack as deep as the chain; Morris does not.

  • Interview follow-ups

    “Do it in O(1) space” after the stack solution is a standard follow-up on inorder traversal and on “validate a binary search tree” and “k-th smallest element”, since both reduce to an inorder walk.

  • Recovering a corrupted BST

    Finding two swapped nodes in a search tree needs the inorder sequence only to spot where it decreases. Morris produces that sequence without extra memory, with the threads restored afterwards.

  • The idea in general

    Borrow something the structure already has, mark it, and undo it. The same trick, temporarily reversing pointers while walking, appears in some garbage-collector marking phases that cannot afford a stack.

SOLVE IT YOURSELF

Solve it: inorder traversal in O(1) space

Every inorder traversal needs a stack — recursion just hides it. Morris traversal borrows the tree’s own empty right pointers instead, and gives them back. Python or TypeScript, running for real in your browser.

YOUR TASK

Implement morris_inorder(root): return the inorder values using no recursion and no stack — O(1) extra space. The tree must be left exactly as you found it.

HINTS — 6 IDEAS
  1. At each node with no left child: record it and step right. That part is easy.
  2. With a left child, find its inorder predecessor — go left once, then right as far as possible.
  3. If that predecessor’s right pointer is empty, thread it back to the current node and descend left. The thread is your way home.
  4. If it already points at the current node, you have returned via that thread: remove it, record the current node, and step right.
  5. Removing the thread is not optional. Skip it and you leave a cycle in the tree — the traversal still prints correctly the first time, then loops forever on the second run. The tests check exactly this.
  6. Stop the predecessor search on pred.right is not cur, or you follow your own thread into an infinite loop.
CPython · WebAssembly

Keep going

▶  Watch it explained

Morris Traversal: Time and Space Complexity, From First Principles

Finished this one? 0 / 99 Algorithms done
NextTwo Nodes, Climbing to Meet: LCA with Binary Lifting Next on the “Walking a tree cleverly” ladder · rung 2 of 2

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms