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.
- 1 <= number of nodes <= 3 * 10⁴
- 0 <= node->data <= 10⁵
- O(1) extra space: no recursion and no stack
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, visitcur, and go right.
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.
Approach
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.
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.
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.
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.
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.
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.
Code in Python, C++ and Java
Common pitfalls
Dropping the "is not cur" test in the predecessor walk
while pred.right:
pred = pred.rightwhile pred.right and pred.right is not cur:
pred = pred.rightOn 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
if pred.right is None:
res.append(cur.data)
pred.right = cur
cur = cur.leftif pred.right is None:
pred.right = cur
cur = cur.leftAppending 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
if len(res) == k:
return res[-1]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.
Edge cases
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.
The predecessor test compares nodes, not values, so equal values never confuse a real right child with a thread.
Complexity
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).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.