The algorithm
void morrisInorder(Node root) {
Node cur = root;
while (cur != null) {
if (cur.left == null) {
visit(cur);
cur = cur.right;
} else {
Node pred = cur.left;
while (pred.right != null && pred.right != cur) pred = pred.right;
if (pred.right == null) {
pred.right = cur; // thread
cur = cur.left;
} else {
pred.right = null; // untread
visit(cur);
cur = cur.right;
}
}
}
}Advertisement
How it works
Find in-order predecessor (rightmost of left subtree). Point its right to current. Descend left. When you come back through the thread, unthread + visit + go right.
Advertisement
Complexity
O(N) time (each node visited constant times), O(1) space.
Tree mutation during
Threads modify + restore. Not thread-safe for concurrent access.