GeeksforGeeks Hard

Morris Preorder Traversal

Morris Preorder Traversal is a GFG problem (Hard). Given the root of a binary tree, return its preorder traversal: the node first, then its left subtree, then its right subtree.

  • The walk may use only O(1) extra space, so no recursion and no stack. The returned list is not counted.
  • Pointers may be changed during the walk, as long as every one is restored before you return.
Constraints
  • 1 <= number of nodes <= 3 * 10⁴
  • 0 <= node->data <= 10⁵
  • O(1) extra space: no recursion and no stack
treemorristhreading
Open on GeeksforGeeks ↗
02

Intuition

A stack-based preorder remembers where each right subtree starts. The Morris walk keeps that memory in the tree instead.

Before entering the left subtree of cur, find the node that finishes it: the rightmost node of cur.left. Nothing hangs off its right side, so aim that empty pointer at cur. When the walk reaches that node later, the borrowed link leads straight back to cur, and from there the walk turns right.

Preorder writes cur at the moment the link is laid, because a node must come before everything in its left subtree. Meeting the link a second time only removes it.

How to spot this pattern

When a preorder walk may use neither recursion nor a stack, only O(1) extra space, the answer is the Morris walk. It also fits problems that flatten or serialise a tree in preorder while being told not to use extra memory.

03

Approach

Try it first

Before reading on, work out which node of cur's left subtree is written last in preorder, and why its right pointer is free to borrow. Then decide at which of the two arrivals at cur the value should be written.

1

Write a node that has no left child

If cur.left is empty there is no left subtree to come back from. Write cur and move to cur.right, which is either a real child or a link that returns the walk to an ancestor.

2

Find the node that ends the left subtree

From cur.left, move right while the right pointer is set and is not cur. You stop either at the rightmost node, whose right pointer is empty, or at the node already linked back to cur.

3

First arrival: write, link, go left

If that right pointer is empty, this is the first time at cur. Write cur now, set the pointer to cur, and move to cur.left. Writing here puts cur ahead of its whole left subtree, which is exactly preorder.

4

Second arrival: unlink and go right

If the pointer already holds cur, the walk has finished the left subtree and climbed back. Set the pointer to empty and move to cur.right, writing nothing: cur went into the answer on its first arrival.

5

Why every node is written exactly once

Links only ever point at nodes that have a left child. So a node without one is reached once and written in the first branch, and a node with one is reached twice and written only on the first of those arrivals.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def preOrder(self, root):
▶3 res = []
▶4 cur = root
▶5 while cur:
▶6 if cur.left is None:
▶7 res.append(cur.data)
▶8 cur = cur.right
▶9 else:
▶10 pred = cur.left
▶11 while pred.right and pred.right is not cur:
▶12 pred = pred.right
▶13 if pred.right is None:
▶14 res.append(cur.data)
▶15 pred.right = cur
▶16 cur = cur.left
▶17 else:
▶18 pred.right = None
▶19 cur = cur.right
▶20 return res
nodeleftrightarrivalscur123pred2453emptyempty4emptyempty5emptyemptypreorder answerat 1: start the search at its left child 2
cur1arrival 1
pred2left child
Row 1 has a left child, so first find the node that ends its left subtree: begin at 2 and keep taking right pointers. This is the first time the walk is at 1.
nodeleftrightarrivalscur1232453emptyempty4emptyemptypred5emptyemptypreorder answer2's right pointer is 5 → move to 5
cur1
pred5one step right
Row 2 has a real right child, so the left subtree does not end there. Step right to 5.
nodeleftrightarrivalscur1232453emptyempty4emptyemptypred5emptylink to 1preorder answer15's right is empty → write 1, link 5 to it
write1first arrival
link5 → 1borrowed pointer
Row 5 ends the left subtree and its right pointer is empty, so this is the first arrival at 1. Preorder needs 1 before its left subtree, so write it now. Then borrow 5's right pointer as a link back to 1 and go left to 2.
nodeleftrightarrivals123cur2453emptyemptypred4emptyempty5emptylink to 1preorder answer1at 2: start the search at its left child 4
cur2arrival 1
pred4left child
Row 2 has a left child, so first find the node that ends its left subtree: begin at 4 and keep taking right pointers. This is the first time the walk is at 2.
nodeleftrightarrivals123cur2453emptyemptypred4emptylink to 25emptylink to 1preorder answer124's right is empty → write 2, link 4 to it
write2first arrival
link4 → 2borrowed pointer
Row 4 ends the left subtree and its right pointer is empty, so this is the first arrival at 2. Preorder needs 2 before its left subtree, so write it now. Then borrow 4's right pointer as a link back to 2 and go left to 4.
nodeleftrightarrivals1232453emptyemptycur4emptylink to 25emptylink to 1preorder answer1244 has no left child → write 4, follow its link
cur4no left child
answer[1, 2, 4]
Row 4 has no left child, so there is no left subtree to write first: write it now. Its right pointer is a borrowed link, so the walk follows it back up to 2.
nodeleftrightarrivals123cur2453emptyemptypred4emptylink to 25emptylink to 1preorder answer124back at 2: start the search at its left child 4
cur2arrival 2
pred4left child
Row 2 has a left child, so first find the node that ends its left subtree: begin at 4 and keep taking right pointers. The walk is back here for the second time, and the search is what will prove it.
nodeleftrightarrivals123cur2453emptyemptypred4emptyempty5emptylink to 1preorder answer1244 links back to 2 → remove it, go right
linkremovedsecond arrival
answer[1, 2, 4]no write
Row 4 already points back at 2, so the walk has finished the left subtree: this is the second arrival. 2 was written on the first arrival, so nothing is written now. Clear the link to restore the tree and go right to 5.
nodeleftrightarrivals1232453emptyempty4emptyemptycur5emptylink to 1preorder answer12455 has no left child → write 5, follow its link
cur5no left child
answer[1, 2, 4, 5]
Row 5 has no left child, so there is no left subtree to write first: write it now. Its right pointer is a borrowed link, so the walk follows it back up to 1.
nodeleftrightarrivalscur123pred2453emptyempty4emptyempty5emptylink to 1preorder answer1245back at 1: start the search at its left child 2
cur1arrival 2
pred2left child
Row 1 has a left child, so first find the node that ends its left subtree: begin at 2 and keep taking right pointers. The walk is back here for the second time, and the search is what will prove it.
nodeleftrightarrivalscur1232453emptyempty4emptyemptypred5emptylink to 1preorder answer12452's right pointer is 5 → move to 5
cur1
pred5one step right
Row 2 has a real right child, so the left subtree does not end there. Step right to 5.
nodeleftrightarrivalscur1232453emptyempty4emptyemptypred5emptyemptypreorder answer12455 links back to 1 → remove it, go right
linkremovedsecond arrival
answer[1, 2, 4, 5]no write
Row 5 already points back at 1, so the walk has finished the left subtree: this is the second arrival. 1 was written on the first arrival, so nothing is written now. Clear the link to restore the tree and go right to 3.
nodeleftrightarrivals123245cur3emptyempty4emptyempty5emptyemptypreorder answer124533 has no left child → write 3
cur3no left child
answer[1, 2, 4, 5, 3]
Row 3 has no left child, so there is no left subtree to write first: write it now. Its right pointer is empty, so the walk stops.
nodeleftrightarrivals1232453emptyempty4emptyempty5emptyemptypreorder answer12453walk ended → answer: 1, 2, 4, 5, 3
answer[1, 2, 4, 5, 3]
links left0tree restored
The walk ran off the tree. Each node was written exactly once: a row with no left child on its only arrival, and a row with a left child on the first of its two arrivals. Every borrowed pointer is empty again.
05

Common pitfalls

Writing on the second arrival

✗ Wrong
else:
    pred.right = None
    res.append(cur.data)
    cur = cur.right
✓ Right
else:
    pred.right = None
    cur = cur.right

By the second arrival the left subtree is already in the answer, so writing cur here puts it after its left children. With the write moved out of the first branch, [1, 2, 3] gives [2, 1, 3], which is inorder.

Writing in both branches

✗ Wrong
if pred.right is None:
    res.append(cur.data)
    ...
else:
    res.append(cur.data)
    ...
✓ Right
write cur only when
the link is laid

This happens when an inorder version is edited by adding the preorder write without removing the old one. Every node with a left child then appears twice: [1, 2] gives [1, 2, 1].

Leaving out the write for a node with no left child

✗ Wrong
if cur.left is None:
    cur = cur.right
✓ Right
if cur.left is None:
    res.append(cur.data)
    cur = cur.right

Such a node is never linked to, so this branch is its only chance to be written. Every leaf goes missing: [1, 2, 3] gives [1].

06

Edge cases

Only right children, like [1, null, 2, null, 3]

No left subtree exists anywhere, so no link is laid and each node is written by the first branch as the walk moves right.

A node whose left child has a right child, like [1, 2, null, null, 3]

The walk from 2 goes right to 3, so the link runs from 3 back to 1, not from 2. Linking from cur.left itself would overwrite 2's real right pointer and lose node 3.

07

Complexity

Time
O(n)
Space
O(1)
n is the number of nodes. A node with a left child costs two walks down its left subtree's right edges, one to lay the link and one to find it again; no right edge belongs to two such walks, so all walks together stay within about 2n steps. Only cur and pred are stored.
08

Morris Preorder Traversal FAQ

What is the difference between Morris preorder and Morris inorder?

Only where the write happens. Inorder writes cur when the link is removed, after its left subtree; preorder writes it when the link is laid.

Is there a Morris postorder traversal?

Yes, still in O(1) space, but it is more work. Use a dummy node whose left child is the root. On each second arrival at cur, write the right edge path from cur.left down to the predecessor in reverse, by reversing those right pointers, reading them, and reversing them back.

Why is the borrowed right pointer always empty?

The node is the rightmost one in cur.left's subtree, found by moving right until there is nowhere to go. If it had a right child, the walk would have moved on to that child.