Write a program that performs Morris inorder traversal of a binary tree.
- User
Write a program that performs Morris inorder traversal of a binary tree.
Assistant
Write a program that performs Morris inorder traversal of a binary tree.
The user wants a program that implements Morris Inorder Traversal for a binary tree.
Understand the Goal: The objective is to traverse a binary tree in-order (Left -> Root -> Right) without using recursion or a stack (which usually takes space, where is the height of the tree). Morris Traversal achieves space complexity by utilizing threaded binary tree concepts (temporarily modifying the tree structure).
Recall/Verify Morris Inorder Traversal Logic:
current, initialized to the root.current is not NULL.current has no left child.
current.current to its right child.current has a left child.
current. The predecessor is the rightmost node in current's left subtree.NULL.
predecessor->right point to current.current to its left child.current.
predecessor->right to NULL.current.current to its right child.Choose the Language: Python is generally easy to read and pseudocode-like, but C++ or Java are also standard for data structures. I will provide the solution in Python as it's concise, and maybe include C++ if appropriate, or stick to Python for clarity unless specified otherwise. The prompt doesn't specify a language, so Python is a safe default, but providing C++ is helpful for students. Let's stick to Python for the primary explanation and code, perhaps adding a C++ version for completeness if the response feels too short, but usually one working example is enough. Let's provide Python. It's widely used.
Structure the Code:
TreeNode class.morris_inorder_traversal(root) function.Drafting the Python Code (Mental or Scratchpad):
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def morris_inorder(root):
curr = root
while curr:
if curr.left is None:
print(curr.val) # Visit
curr = curr.right
else:
# Find predecessor
pre = curr.left
while pre.right and pre.right != curr:
pre = pre.right
if pre.right is None:
pre.right = curr # Create thread
curr = curr.left
else:
pre.right = None # Remove thread
print(curr.val) # Visit
curr = curr.right
Refining the Code:
Complexity Analysis:
Final Output Generation:
Self-Correction/Double Check:
pre.right is already curr? Yes, the inner while loop stops.Morris Traversal allows you to traverse a binary tree inorder without using recursion or a stack. It achieves O(1) space complexity by temporarily modifying the tree structure (creating "threads" from a predecessor node to the current node) and then restoring it.
Steps:
current pointer to the root.current is not NULL:
current has no left child:
current's value.current to its right child.current has a left child):
current (the rightmost node in the current node's left subtree).NULL: This means we haven't visited the left subtree yet. Set the predecessor's right child to current (create the thread) and move current to its left child.current: This means we have finished visiting the left subtree. Revert the changes (set predecessor's right child back to NULL), print/process current's value, and move current to its right child.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def morris_inorder_traversal(root):
current = root
while current is not None:
if current.left is None:
# If there is no left child, process current and go right
print(current.val, end=" ")
current = current.right
else:
# Find the inorder predecessor of current
# (The rightmost node in the left subtree)
predecessor = current.left
while predecessor.right is not None and predecessor.right != current:
predecessor = predecessor.right
# Case 1: Predecessor's right is None
# We are visiting this node for the first time.
# Make a temporary link (thread) from predecessor to current.
if predecessor.right is None:
predecessor.right = current
current = current.left
# Case 2: Predecessor's right is already pointing to current
# This means we have visited the left subtree.
# Break the link, process current, and go right.
else:
predecessor.right = None
print(current.val, end=" ")
current = current.right
print() # Newline for clean output
# --- Example Usage ---
if __name__ == "__main__":
# Constructing the following tree:
# 4
# / \
# 2 5
# / \
# 1 3
root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(5)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
print("Morris Inorder Traversal:")
morris_inorder_traversal(root)
Morris Inorder Traversal:
1 2 3 4 5
while loop inside another while loop, every edge of the tree is traversed at most three times (once to establish the thread, once to process the node, and once to remove the thread). Therefore, the total time complexity is linear.current, predecessor).if not leftwhile pre.right and pre.right != curr.pre becomes Root? No pre starts at Left2. pre.right is Root. pre.right is not None. Loop checks pre.right != curr. Here Root != Left1. Loop continues?pre = pre.right. pre becomes Root. Root has no right? Or maybe it does. This logic is tricky.pre = curr.left. While pre.right exists AND pre.right != curr: pre = pre.right.pre.right != curr (L1 != L1) is False. Loop terminates.pre.right is L1 (not None). So we are in the "thread exists" block.L1.right != Root? False. Stop.pre.right is Root. Thread exists. Break L1->Root. Print Root. Curr=Root->right (None).Writing the response: Present clearly. Use Python code block.
(Self-Correction during drafting): I should make sure the variable names are clear. current is better than root inside the function. predecessor is better than pre.
Let's write the explanation.
current as root.current is not NULL:
a. If current has no left child:
current.current's left subtree (inorder predecessor).current (create thread).current to left child.current):
current.current to right child.This covers everything. Here is a complete implementation of the Morris Inorder Traversal in Python.