While current is not None: push current onto stack; current = current.left.
Pop node from stack, append its value to result.
Set current = popped_node.right.
Return result.
Provide example usage building a tree and calling both functions.
We'll present the code with comments.
python
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_recursive(root):
"""Return the in-order traversal as a list using recursion."""
if not root:
return []
return inorder_recursive(root.left) + [root.val] + inorder_recursive(root.right)
def inorder_iterative(root):
"""Return the in-order traversal as a list using iteration (stack)."""
stack = []
result = []
current = root
while current or stack:
# Go to the leftmost node
while current:
stack.append(current)
current = current.left
# Process the node
node = stack.pop()
result.append(node.val)
# Move to the right subtree
current = node.right
return result
# Example usage
if __name__ == "__main__":
# Construct the tree:
# 1
# / \
# 2 3
# / \
# 4 5
root = TreeNode(1,
TreeNode(2,
TreeNode(4),
TreeNode(5)),
TreeNode(3))
print("Recursive inorder:", inorder_recursive(root)) # Output: [4, 2, 5, 1, 3]
print("Iterative inorder:", inorder_iterative(root)) # Output: [4, 2, 5, 1, 3]