GeeksforGeeks Hard

Morris Inorder Traversal

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

  • Use O(1) extra space: no recursion and no stack. The answer list itself does not count.
  • You may change pointers while you walk, but the tree must be back in its original shape when 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 normal inorder walk needs a stack only to climb back to a node after finishing its left subtree. The Morris walk stores that way back inside the tree.

The last node visited in the left subtree of cur is its inorder predecessor: the rightmost node of cur.left. Being rightmost, its right pointer is always empty, so it can be borrowed. Point it at cur. This temporary link is called a thread.

  • First arrival at cur: no thread yet, so the left subtree has not been walked. Lay the thread and go left.
  • Second arrival: the thread already points at cur, so the left subtree is done. Cut the thread, visit cur, and go right.
How to spot this pattern

When an inorder walk may use neither recursion nor a stack, only O(1) extra space, the answer is Morris traversal. It also turns up inside other problems that walk a BST in sorted order, such as finding the k-th smallest value or repairing two swapped nodes.

03

Approach

Try it first

Before reading on, decide where the walk can store the way back to cur once its left subtree is finished, given that you may not use a stack. Then decide how the walk can tell, on reaching cur again, whether its left side is still to do or already done.

1

Visit a node with no left child

If cur.left is empty, nothing comes before cur inside its own subtree, so append it to the answer and move to cur.right. That right pointer is either a real child or a thread that leads back up to an ancestor.

2

Find the inorder predecessor

Otherwise step to cur.left and keep moving right while the right pointer is set and is not cur. The walk stops at the rightmost node of the left subtree, or at the node whose thread already points back at cur.

3

First arrival: lay the thread and go left

If the predecessor's right pointer is empty, set it to cur and move to cur.left. Do not visit cur yet: inorder puts every node of the left subtree first, and the thread is how the walk will get back here afterwards.

4

Second arrival: cut the thread and visit

If the predecessor's right pointer is cur, the walk has just come back up along that thread, so the whole left subtree is done. Set the pointer back to empty, append cur, and move to cur.right.

5

Why the tree ends up unchanged

A node with a left child is reached exactly twice: once from above and once along its own thread. The thread is laid on the first visit and cut on the second, so when cur finally runs off the right end of the tree, every borrowed pointer is empty again.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def inOrder(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 pred.right = cur
▶15 cur = cur.left
▶16 else:
▶17 pred.right = None
▶18 res.append(cur.data)
▶19 cur = cur.right
▶20 return res
thread1cur2pred345inorder answerlook for 1's predecessor: start at 2
cur1has a left child
pred2cur's left child
1 has a left subtree, so its inorder predecessor is the rightmost node of that subtree. Start at the left child, 2.
thread1cur2345predinorder answer2 has a right child → move to 5
cur1
pred5one step right
2 still has a right child, so it is not the rightmost node yet. Move right to 5.
thread1cur2345predinorder answer5's right is empty → thread it to 1, go left
thread5 → 1first arrival
answer[]
5 is the predecessor and its right pointer is free, so this is the first arrival at 1. Point it at 1 so the walk can climb back later, then go left. 1 is not written yet: its left subtree comes first in inorder.
thread12cur34pred5inorder answerlook for 2's predecessor: start at 4
cur2has a left child
pred4cur's left child
2 has a left subtree, so its inorder predecessor is the rightmost node of that subtree. Start at the left child, 4.
thread12cur34pred5inorder answer4's right is empty → thread it to 2, go left
thread4 → 2first arrival
answer[]
4 is the predecessor and its right pointer is free, so this is the first arrival at 2. Point it at 2 so the walk can climb back later, then go left. 2 is not written yet: its left subtree comes first in inorder.
thread1234cur5inorder answer44 has no left child → write 4
cur4no left child
answer[4]
Nothing sits to the left of 4 inside its own subtree, so it is next in inorder: write it. Its right pointer is a thread, so following it climbs back to 2.
thread12cur34pred5inorder answer4back at 2: look for 2's predecessor: start at 4
cur2has a left child
pred4cur's left child
The walk came back to 2 along a thread. It cannot tell yet whether this is the first or second arrival, so it finds the predecessor again. 2 has a left subtree, so its inorder predecessor is the rightmost node of that subtree. Start at the left child, 4.
thread12cur34pred5inorder answer244 points back to 2 → cut it, write 2
threadcutsecond arrival
answer[4, 2]
The predecessor 4 already points at 2, so this is the second arrival: the whole left subtree has been written. Remove the thread to restore the tree, write 2, and go right to 5.
thread12345curinorder answer2455 has no left child → write 5
cur5no left child
answer[4, 2, 5]
Nothing sits to the left of 5 inside its own subtree, so it is next in inorder: write it. Its right pointer is a thread, so following it climbs back to 1.
thread1cur2pred345inorder answer245back at 1: look for 1's predecessor: start at 2
cur1has a left child
pred2cur's left child
The walk came back to 1 along a thread. It cannot tell yet whether this is the first or second arrival, so it finds the predecessor again. 1 has a left subtree, so its inorder predecessor is the rightmost node of that subtree. Start at the left child, 2.
thread1cur2345predinorder answer2452 has a right child → move to 5
cur1
pred5one step right
2 still has a right child, so it is not the rightmost node yet. Move right to 5.
thread1cur2345predinorder answer12455 points back to 1 → cut it, write 1
threadcutsecond arrival
answer[4, 2, 5, 1]
The predecessor 5 already points at 1, so this is the second arrival: the whole left subtree has been written. Remove the thread to restore the tree, write 1, and go right to 3.
thread123cur45inorder answer123453 has no left child → write 3
cur3no left child
answer[4, 2, 5, 1, 3]
Nothing sits to the left of 3 inside its own subtree, so it is next in inorder: write it. Its right pointer is empty, so the walk is over.
thread12345inorder answer12345walk ended → answer: 4, 2, 5, 1, 3
answer[4, 2, 5, 1, 3]
threads left0tree restored
cur ran off the right end of the tree. Every node was written once, in left-to-right order, which is why the answer row filled from left to right. No threads remain, so the tree is back to its original shape.
05

Common pitfalls

Dropping the "is not cur" test in the predecessor walk

✗ Wrong
while pred.right:
    pred = pred.right
✓ Right
while pred.right and pred.right is not cur:
    pred = pred.right

On the second arrival the predecessor's right pointer is the thread itself. Without the test the walk follows it back to cur and keeps going. On the tree [2, 1] it ends on node 2, threads 2 to itself, and the loop never stops.

Visiting on the first arrival

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

Appending cur before its left subtree is preorder, not inorder. For the tree [1, 2, 3] it returns [1, 2, 3] instead of [2, 1, 3]. In inorder the append belongs in the branch that cuts the thread.

Stopping the walk early

✗ Wrong
if len(res) == k:
    return res[-1]
✓ Right
keep walking until cur is None,
then return the k-th value

Problems like k-th smallest in a BST are tempting to cut short. But threads laid above the stopping point are still in place. For [2, 1, 3] with k = 1, returning at node 1 leaves 1's right pointer aimed at 2, so the tree now has a cycle.

06

Edge cases

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

No node has a left child, so no thread is ever laid. Every step takes the first branch and the walk is a plain loop down the right side.

Repeated values, like [1, 1, 1]

The predecessor test compares nodes, not values, so equal values never confuse a real right child with a thread.

07

Complexity

Time
O(n)
Space
O(1)
n is the number of nodes. The only extra memory is the two pointers cur and pred; the answer list is not counted. The predecessor walks look like extra work, but together they cover each edge at most twice (see the FAQ).
08

Morris Inorder Traversal FAQ

Why is Morris traversal O(n) and not O(n log n)?

Each predecessor walk for cur takes one step left and then follows right edges down the right-hand side of that left subtree. A right edge lies on that right-hand side for only one node cur, so no two walks share an edge. Each walk runs twice, once to lay the thread and once to find it again, so all walks together cover at most about 2n edges.

What is the downside of Morris traversal?

It writes to the tree while it reads it. The tree cannot be read-only or shared with another thread during the walk, and an exception mid-walk leaves threads behind. It is also slower in practice than a stack walk, because every node with a left child costs two predecessor walks.

How does Morris preorder traversal differ?

The threading is identical. Preorder appends cur when the thread is laid, on the first arrival, and the cut branch appends nothing.