Sub topic 18
Morris traversal: O(1) extra space
This chapter assumes you know the recursive and stack-based inorder traversals, how a binary tree node stores left and right, and Big-O basics.
The problem it solves
Recursive and stack-based traversals need memory proportional to the tree height. That is O(log n) for a balanced tree and O(n) for a degenerate one. The memory holds the way back to ancestors whose right subtrees are still unvisited.
Morris traversal stores that way back inside the tree. A leaf-like node on the left side has a right pointer that is None. The algorithm temporarily points it at the ancestor that should be visited next. This pointer is called a thread. Once the thread has been followed, the algorithm removes it, and the tree is restored.
The algorithm
For the current node:
- If it has no left child, visit it and move right. The right pointer may be a thread.
- Otherwise find its inorder predecessor: the rightmost node in its left subtree.
- If the predecessor's
rightisNone, set it to the current node (create the thread) and move left. - If the predecessor's
rightis the current node, the left subtree is finished. Remove the thread, visit the current node, and move right.
Code
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def morris_inorder(root):
result = []
current = root
while current is not None:
if current.left is None:
result.append(current.value)
current = current.right
else:
pred = current.left
while pred.right is not None and pred.right is not current:
pred = pred.right
if pred.right is None:
pred.right = current # create thread
current = current.left
else:
pred.right = None # remove thread
result.append(current.value)
current = current.right
return result
root = Node(1, Node(2, Node(4), Node(5)), Node(3))
print(morris_inorder(root)) # [4, 2, 5, 1, 3]The output matches the recursive inorder result. Node 5 is the predecessor of node 1, so after 5 is visited, its thread leads back to 1.
Cost
Each edge on a left subtree's right spine is walked about twice, once to create a thread and once to remove it. The total time is still O(n). The extra space is O(1), because only current and pred are kept. The result list is output, not working memory.
Gotchas
- The tree is modified during the walk. Another thread reading the tree at the same time can see cycles.
- An exception or early
breakleaves threads behind. The tree then contains cycles. Always run the loop to completion. - The constant factor is higher. Predecessor searches repeat work that a stack avoids.
- Preorder is a small change. Visit the node when you create the thread, and when it has no left child. Postorder is much harder.
Exercise
In morris_inorder, why does the predecessor search stop when pred.right is current?
Show answer
That condition means a thread from an earlier visit already exists, so the left subtree has been fully traversed. Without the check, the loop would follow the thread back to current and never end. The algorithm then removes the thread, visits the node, and moves right.