In-order traversal is a way to systematically visit every node in a binary tree using the order: left subtree → node → right subtree. It is one of the three classic depth-first traversals, alongside pre-order and post-order.
For a binary search tree (BST), in-order traversal yields the node values in sorted order. This property underpins many BST operations and interview problems.
4
/ \
2 6
/ \ / \
1 3 5 7
In-order sequence: 1, 2, 3, 4, 5, 6, 7
function inorder(node):
if node is null:
return
inorder(node.left)
visit(node) # e.g., print node.value or collect it in a list
inorder(node.right)
Time complexity: O(n) visits each node once.
Space complexity: O(h) call stack, where h is the tree height (O(log n) for balanced trees, O(n) for skewed trees).
function inorder_iterative(root):
stack = empty stack
curr = root
while curr is not null or stack is not empty:
# Go as left as possible
while curr is not null:
stack.push(curr)
curr = curr.left
# Visit node
curr = stack.pop()
visit(curr)
# Traverse right subtree
curr = curr.right
This avoids recursion and gives the same O(n) time with O(h) explicit stack space.
Morris traversal creates temporary “threads” to predecessors to traverse without a stack or recursion:
function inorder_morris(root):
curr = root
while curr is not null:
if curr.left is null:
visit(curr)
curr = curr.right
else:
# Find rightmost of left subtree (predecessor)
pred = curr.left
while pred.right is not null and pred.right != curr:
pred = pred.right
if pred.right is null:
pred.right = curr # create thread
curr = curr.left
else:
pred.right = null # remove thread
visit(curr)
curr = curr.right
Morris traversal runs in O(n) time and O(1) extra space, but temporarily modifies pointers during execution.