Morris traversal: O(1) space by threading the tree

Video lessonComing soon

1 The stack remembers the way back up

The last two lessons walked a tree in two ways. Recursion kept its notes on the call stack, and the iterative walk kept them on a stack of our own. Each note is a way back up. When the walk finishes a left subtree, a note says which node to return to.

Those notes cost O(h) space, where h is the height. On a chain of 10⁵ nodes, the stack holds 10⁵ of them. Some problems ask for O(1) extra space instead: a few variables, and nothing that grows with the tree.

The tree has room to spare. A tree of n nodes has n + 1 null pointers, and our running tree has 7:

425136
6 nodes, 7 nulls: two under each leaf, one left of 3

Morris traversal borrows some of these nulls. Before the walk goes down into a node's left subtree, it ties a thread from the bottom of that subtree back up to the node. A climber does the same with a rope before going down into a cave. Later the walk climbs the thread back up and removes it.

2 Where the way back is needed

In inorder, node 1 waits for its whole left subtree: 4, 2 and 5. After the last of them, 5, the walk must get back to 1. So the way back is needed in one place: the last node the left subtree writes.

That node is the rightmost node of the left subtree. From 1, we step left to 2, then go right as far as we can, and stop at 5. It comes just before 1 in inorder, so it is 1's inorder predecessor, pred in the code.

425136
From 1: left to 2, then right to 5
425136
5's empty right pointer now leads to 1

The predecessor has no right child, or the search would have gone further. So its right pointer is free, and we point it at 1. This borrowed pointer is a thread. After the walk writes 5, it goes right as usual, and the thread takes it back to 1.

Node 2 needs a thread too, from its predecessor 4. Nodes 3 to 6 have no left child, so nothing waits for them.

NodeLeft childPredecessorThread
1255.right → 1
2444.right → 2

With the threads in place, going right after a write always leads where inorder goes next: down into a right subtree, or up a thread to the node that was waiting.

3 Two visits, told apart by the thread

The walk moves one pointer, current. A node with a left child is reached twice: on the way down, and when its thread brings the walk back up. The predecessor's right pointer tells the two apart:

  • No left child. Nothing waits, so we write current and go right.
  • pred.right is null: the first visit. The left subtree is still to do. We tie the thread, pred.right = current, and go left.
  • pred.right is current: the second visit. We came back up the thread, so the left subtree is done. We remove the thread, write current and go right.
Start a roundNo left child?Write, go rightpred.right is null?Tie, go leftRemove, write, go rightNext roundNoNoYesYes
One round. pred is the rightmost node of current.left. Rounds repeat until current is null

The predecessor search must stop at current as well as at null. On the second visit, the right path from current.left ends in the thread back to current. A search that stops only at null follows it out of the subtree. So the search moves right while pred.right is neither null nor current.

4 Threading our tree, step by step

Here is the whole walk on our tree. The filled node is current. The four boxes are all the memory the walk uses: current, pred and the two right pointers it borrows. Orange marks a thread that is in place.

Morris inorder on our tree
425136
1current5prednull4.right15.right
Tie 5 → 1, go left to 2
values

The same walk as a table, one row per round:

Roundcurrentpredpred.right wasWhat happensvalues
115nulltie 5 → 1, go left
224nulltie 4 → 2, go left
34––write, climb to 24
4242remove 4 → 2, write, go right4 2
55––write, climb to 14 2 5
6151remove 5 → 1, write, go right4 2 5 1
73––write, go right4 2 5 1 3
86––write, right is null: stop4 2 5 1 3 6

Nodes 1 and 2 are current twice, once to tie a thread and once to remove it. In round 4, the search finds the thread the walk climbed in round 3, so it knows 2's left side is done. At the end, both threads are gone.

In code, the predecessor search goes in a small helper:

On our tree, it returns [4, 2, 5, 1, 3, 6] and leaves the tree as it was. On an empty tree, the loop never starts.

C++

Compare pointers. pred->right != current compares addresses, so it asks for the same node, not for an equal value. Two nodes can hold the same value.

!= compares references. pred.right != current asks for the same node, not for an equal value. Two nodes can hold the same value.

is not compares identity. pred.right is not current asks for the same node object, not for an equal value. Two nodes can hold the same value.

!== on objects compares identity. pred.right !== current asks for the same node, not for an equal value. Two nodes can hold the same value.

Pointers compare by address. pred.Right != current asks for the same node, not for an equal value. Two nodes can hold the same value.

Rc::ptr_eq compares nodes. It asks whether two Rcs point to the same node. A thread is a second Rc to node, so it makes a cycle for a while. The second visit removes it, so nothing leaks.

!= compares references. pred.right != current asks for the same node, not for an equal value. Two nodes can hold the same value.

5 Preorder: write on the first visit

Preorder writes a node when the walk first arrives. In the Morris walk, that is the round that ties the node's thread, before the walk goes left. So preorder moves one write, from the second visit to the first. A node with no left child is written as before.

CaseInorder writesPreorder writes
No left childyesyes
First visit: tie the threadnoyes
Second visit: remove the threadyesno

On our tree, the writes now come in rounds 1, 2, 3, 5, 7 and 8. They give 1 2 4 5 3 6. The threads are tied and removed exactly as before, so the tree comes back whole.

Postorder has a Morris version too. It writes each finished right path backwards. The code is fiddly, so we leave it out.

6 Cost: O(n) time, O(1) space

Space. The walk keeps current and pred, and nothing else. The threads use pointers that were null already, so they take no new memory. On a chain of 10⁵ nodes, the walk still uses two variables. That is O(1) extra space. The list of values is the answer, so we do not count it.

Time. current reaches each node at most twice. A predecessor search can be long, but it walks only the right side of one left subtree, from current.left down. No other node's search uses those edges, and each search runs at most twice. So every edge is walked a few times at most, and the whole walk is O(n).

The tree comes back whole. Every thread starts at the last node of a left subtree. The walk always reaches that node, writes it and climbs the thread. The climb brings the walk back to the waiting node for its second visit, and that visit removes the thread. So by the end, every pointer is as it was.

7 Mistakes and edge cases

  • Forgetting to remove the thread. The values still come out right, but the tree keeps 4.right → 2 and 5.right → 1. The next walk over it loops. A plain recursive inorder calls 2, 4, 2, 4 without end, and stops with a Runtime Error.
  • A search that stops only at null. On the second visit to 2, the search climbs the thread from 4 and runs on through 2, 5, 1, 3 and 6. It ties a wrong thread at 6 and writes 4 a second time. The next search goes round 2 5 1 3 6 for ever, and that is TLE.
  • Writing at the wrong moment. Writing on the first visit instead of the second gives 1 2 4 5 3 6, the preorder. Writing on both visits gives 1 2 4 2 5 1 3 6. Either way, it is Wrong Answer.
  • Comparing values instead of nodes. On the tree [1, 2, null, null, 1], 2's real right child also holds 1. A search that compares values stops there and takes that child for a thread. The walk cuts it off and returns 1 instead of 2 1 1.

8 When to use Morris traversal

The sign is the same as for every walk in this part: a problem must visit every node in a set order. Morris is the answer when the problem also asks for O(1) extra space, or forbids both recursion and a stack. Otherwise, the recursive or stack walk is shorter and safer.

Before choosing it, check two things:

  • Nothing else reads the tree during the walk. For a while, some right pointers point back up. Another part of the program that reads the tree then sees cycles. A tree we may not change rules Morris out.
  • The walk runs to the end. A search that stops at the answer leaves threads behind. To stop early, carry on walking without writing until current is null, so every thread is removed.

The next lesson moves from visiting nodes to working with them: what a recursive call on a tree should return.

Before writing a Morris walk, find the line that removes each thread. Every thread tied must be removed, even when the answer comes early.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.