class Node: def __init__(self, val): self.val = val self.left = None self.right = None def morris_inorder(root): result = [] current = root while current: if current.left is None: result.append(current.val) current = current.right else: pre = current.left while pre.right and pre.right != current: pre = pre.right if pre.right is None: pre.right = current current = current.left else: pre.right = None result.append(current.val) current = current.right return result root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print(morris_inorder(root))
The Morris inorder traversal visits nodes in the order: left subtree, current node, right subtree without using stack or recursion.
For the given tree, the inorder sequence is 4, 2, 5, 1, 3.
The temporary thread allows the traversal to return to the current node after finishing the left subtree without using stack or recursion.
This thread is removed after use, so the tree remains unchanged.
def morris_inorder_bug(root): result = [] current = root while current: if current.left is None: result.append(current.val) current = current.right else: pre = current.left while pre.right != None and pre.right != current: pre = pre.right if pre.right == None: pre.right = current current = current.left else: # Missing line to remove thread result.append(current.val) current = current.right return result
The code misses the line that removes the temporary thread (pre.right = None).
This causes the traversal to revisit the same nodes endlessly, resulting in an infinite loop.
In Morris traversal, each node except the rightmost node in inorder is visited twice: once when first reached, and once when returning via the temporary thread.
Thus, N-1 nodes are visited twice.
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def morris_inorder(root): result = [] current = root while current: if current.left is None: result.append(current.val) current = current.right else: pre = current.left while pre.right and pre.right != current: pre = pre.right if pre.right is None: pre.right = current current = current.left else: pre.right = None result.append(current.val) current = current.right return result root = Node(10) root.left = Node(5) root.right = Node(15) root.left.left = Node(2) root.left.right = Node(7) root.right.left = Node(12) root.right.right = Node(20) root.left.left.left = Node(1) root.left.left.right = Node(3) print(morris_inorder(root))
The Morris inorder traversal visits nodes in ascending order for this binary search tree.
The correct inorder sequence is [1, 2, 3, 5, 7, 10, 12, 15, 20].
