Previous Topic
tree_traversal_algorithm
0.82
Provides a deterministic DFS ordering that captures hierarchical structure needed for serialization and deserialization routines.

In Order Traversal

data structures algorithms programming fundamentals software engineering
In-order traversal is a depth-first algorithm for visiting all nodes of a binary tree in a specific order: left subtree, current node, then right subtree. It is especially useful for binary search trees (BSTs), where it outputs the keys in non-decreasing (sorted) order. The method can be implemented recursively, iteratively with a stack, or with Morris traversal for O(1) extra space.

What Is In-Order Traversal?

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.

Example

        4
      /   \
     2     6
    / \   / \
   1   3 5   7

In-order sequence: 1, 2, 3, 4, 5, 6, 7

Recursive Algorithm

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).

Iterative Algorithm (Using a Stack)

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 (O(1) Extra 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.

Why It Matters

  • Sorted output for BSTs: Extracts keys in non-decreasing order.
  • Order-sensitive tasks: Find the k-th smallest element, merge/convert BSTs to arrays, or generate sorted lists.
  • Validation: Check if a tree is a valid BST by verifying the in-order sequence is non-decreasing.
  • Expression trees: Produces infix notation from binary expression trees (with parentheses as needed).

Common Pitfalls

  • Forgetting the base case (null check) in recursion.
  • Accidentally using pre-order or post-order ordering.
  • Stack overflow on very deep/skewed trees when using recursion; prefer iterative methods or ensure balanced trees.
  • Handling duplicates in BSTs: ensure a consistent policy (e.g., left subtree holds <= or < keys).

Edge Cases

  • Empty tree: Visit nothing.
  • Single node: Visit the node itself.
  • Skewed tree: Complexity degrades to O(n) space for recursion/stack; Morris remains O(1) extra space.

Practice Ideas

  • Print a BST in sorted order using recursive and iterative in-order traversal.
  • Return the k-th smallest element in a BST.
  • Validate a BST using in-order traversal with a running previous value.
  • Implement Morris traversal and compare memory usage with the stack-based approach.

Context from Referenced By

Context from Related Topics
Pop Quiz
Topic: in_order_traversal
Level: 1
True or False:

In-order traversal of any binary tree always produces node values in non-decreasing (sorted) order.

Topic: in_order_traversal
Level: 1
Multiple Choice:

Which method allows in-order traversal of a binary tree using O(1) extra space by temporarily threading nodes?

Topic: in_order_traversal
Level: 1
Fill in the Blank:

In-order traversal of a binary tree visits nodes in the _____ order.

Topic: in_order_traversal
Level: 2
True or False:

A recursive in-order traversal of a balanced binary tree uses O(log n) stack space.

Topic: in_order_traversal
Level: 2
Multiple Choice:

For a skewed binary tree with n nodes, what is the worst-case auxiliary space used by a standard recursive in-order traversal?

Topic: in_order_traversal
Level: 2
Fill in the Blank:

An iterative in-order traversal of a binary tree typically uses an explicit _____ to manage nodes.

Topic: in_order_traversal
Level: 3
True or False:

Morris in-order traversal temporarily links a node’s inorder predecessor to the node and must remove that link afterward to restore the original tree structure.

Topic: in_order_traversal
Level: 3
Multiple Choice:

What is the time complexity of Morris in-order traversal on a binary tree with n nodes?

Topic: in_order_traversal
Level: 3
Fill in the Blank:

In-order traversal is a _____ traversal technique.

Topic: in_order_traversal
Level: 4
True or False:

Counting visited nodes during an in-order traversal of a binary search tree lets you return the k-th smallest key without storing the entire traversal.

Topic: in_order_traversal
Level: 4
Multiple Choice:

In Morris in-order traversal, if the current node has a left child and its inorder predecessor's right pointer is null, what should you do next?

Topic: in_order_traversal
Level: 4
Fill in the Blank:

In an iterative in-order traversal, after popping and visiting a node, you proceed to its _____ child.

Topic: in_order_traversal
Level: 5
True or False:

In Morris in-order traversal, if the current node has no left child, you visit it and then move to its right child.

Topic: in_order_traversal
Level: 5
Multiple Choice:

For an iterative in-order traversal of a binary tree that uses an explicit stack, what is the auxiliary space complexity in terms of the tree height h?

Topic: in_order_traversal
Level: 5
Fill in the Blank:

In-order traversal is especially useful for _____ because it produces keys in non-decreasing order.

Next Topic
used_by
0.94

Iterative Tree Traversal
Binary search trees rely on in-order traversal to visit nodes in non-decreasing key order for iteration, range queries, and validation.
used_by
0.94

Sorted Array From Bst
Building a sorted array from a BST collects node keys via in-order visitation, yielding non-decreasing order.
used_by
0.94

Binary Search Trees (Bst)
BSTs use in-order traversal to output keys in non-decreasing order, enabling sorted iteration, range queries, and validation of BST properties.
used_by
0.93

Convert Bst To Sorted List
Conversion of a BST to a sorted list typically leverages in-order traversal to emit keys in non-decreasing order for direct append into the list.
used_by
0.92

Tree To Sorted Array
Creating a sorted array from a binary search tree appends node values during an in-order traversal to produce non-decreasing order.
used_by
0.92

Kth Smallest In Bst
Finding the kth smallest element in a BST typically performs an in-order traversal and counts visited nodes until the kth is reached, leveraging the traversal's sorted visitation order.
defines
0.92

Inorder Successor
The inorder successor of a node in a BST is the node that appears immediately after it in the left-root-right visitation order; algorithms to find it are derived from the properties of in-order traversal.
used_by
0.9

Validate Bst
Validating a BST often uses in-order traversal to ensure the visited node values form a non-decreasing sequence, enabling an O(n) correctness check.
used_by
0.9

Binary Search Tree Operations
BST operations such as producing sorted output, range queries, successor/predecessor lookups, and k-th smallest often invoke in-order traversal to leverage its sorted visitation order.
used_by
0.9

Bst Validation
BST validation leverages in-order traversal to check that the sequence of visited keys is non-decreasing, confirming the BST ordering property.
used_by
0.9

Range Query In Bst
BST range queries output all keys within [lo, hi] by using in-order traversal to visit nodes in sorted order and prune subtrees outside the range.
used_by
0.9

Expression Trees Infix
Converting a binary expression tree to an infix string relies on visiting left operand, operator, then right operand via in-order traversal (with parentheses handling).
used_by
0.88

Morris Traversal
Morris traversal is a technique to perform in-order traversal using temporary threading to achieve O(1) extra space while preserving the left-root-right visit order.
used_by
0.86

Inorder Iterator
An inorder iterator for a binary tree yields nodes in left-node-right order by applying in-order traversal to generate successive elements.